Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: extracting month and year from a date variable


From   Joseph McDonnell <[email protected]>
To   [email protected]
Subject   Re: st: extracting month and year from a date variable
Date   Thu, 27 Aug 2009 14:07:43 +0930

. list


     +----------------+
      |    mydate  |
      |-----------------|
  1. | 18jul2006   |
  2. | 21aug2006 |
  3. | 05feb2008  |
     +---------------- +

. gen my=string(month(mydate),  "%02.0f")+"_"+string(year(mydate))

will give you the second.

. local mlist c(Mons)

. gen MY=""
. forvalues i=1/12 {
.	local j=(`i'-1)*4+1
.	qui replace MY=substr(`mlist',`j',3)+" "+string(year(mydate)) if
month(mydate)==`i'
. }

will give you the first. The construction for the macro j relates to
the position of the start of the name in the string c(Mons). There's
probably a more efficient way to do it.

. list

     +------------------------------------------------+
      |    mydate        my         MY        |
      |-------------------------------------------------|
  1. | 18jul2006    07_2006   Jul 2006   |
  2. | 21aug2006  08_2006   Aug 2006  |
  3. | 05feb2008   02_2008   Feb 2008  |
     +-------------------------------------------------+

Cheers

Joseph

On Thu, Aug 27, 2009 at 1:06 PM, Ariel Linden,
DrPH<[email protected]> wrote:
> Hi Fellow Stata Listservers,
>
> I am trying to generate a variable that contains only the month and year,
> extracted from another complete date variable. The ultimate intent is to
> aggregate a given outcome by the month/year.
>
> So for example, the original date value is 17374, which is displayed as
> 07/27/2007. I would like to generate a variable that is "Jul 2007" or
> "07_2007" (I am not picky on the style, this is just to allow me to
> aggregrate by this variable).
>
> I get the feeling that I will have to convert this to a string and then
> generate the variable with a substr statement, but I hope there is an easier
> way.
>
> Thanks in advance
>
> Ariel
>
> *
> *   For searches and help try:
> *   http://www.stata.com/help.cgi?search
> *   http://www.stata.com/support/statalist/faq
> *   http://www.ats.ucla.edu/stat/stata/
>

*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index