Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Formatting date variable YYYYMM

    Hi,

    I would appreciate your help with formatting date variables. I use Stata 15.

    I would like to get YYYYMM-variables in a date formate and I used following syntax:

    foreach var of varlist {
    format `var' %12.0g
    tostring `var', gen(junk`var')
    gen junk`var'2 = mofd(date(junk`var', "YM"))
    format junk`var'2 %tm
    }


    Then the result looks like this:
    2010m1
    2010m2
    2010m3
    2010m4
    2010m5
    2010m6
    2010m7
    2010m8
    2010m9
    201010

    I wonder how I can get this result:
    201001
    201002
    201003
    201004
    201005
    201006
    201007
    201008
    201009
    201010

    I have not found any help in the Stata manuals about working with dates and times.

  • #2
    I gather that you want to see say 201905 if a monthly date corresponding a numeric variable is say May 2019. Consider

    Code:
    . help datetime display formats
    
    . di %tmCYN ym(2019, 5)
    201905
    The Stata manuals give a great deal of help.

    Code:
    help datetime
    
    help datetime display formats
    give links to manual entries, although the help is detailed enough to answer questions like these.

    Your syntax is incomplete (no varlist given) but assuming a numeric variable given with values like 201905 then a simpler way to get what you want is

    Code:
    gen wanted = ym(floor(given/100), mod(given, 100))
    format wanted %tm
    You don't have to take the route convert to string -- daily date -- monthly date. The year and month elements are already available for numeric calculations.

    Comment


    • #3

      Thank you very much for your help! Now I could get the dates in correct format.

      Special thanks for the short syntax!

      Comment

      Working...
      X