Announcement

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

  • Getting a date from a numerical variable

    Hello,
    I have a numerical variable x which contains date information (its value is, for example, 27112014 for today’s date).

    I want to convert x into a date variable y using Stata’s date function. However, I cannot run 'gen y=date(x, “DMY”)’ because x needs to be a string variable. How do I convert x into a string? Or, how do I create a date from a numerical variable?

    Thank you,
    Jan


  • #2
    Code:
    gen y=date(string(x, "%12.0f"), “DMY”)
    should work. The format argument is crucial; otherwise Stata will see a string it can't interpret as a date. You just need a format that ensures integer display, not scientific notation.

    Sandbox play:

    Code:
    //  problem lurking
    Code:
    . di string(27112014)
    2.71e+07
    
    // so don't do this! 
    . di %td  date(string(27112014), "DMY")
            .
    
    // a non-missing result 
    . di date(string(27112014, "%10.0f"), "DMY")
    20054
    
    // and we got it right
    . di %td  date(string(27112014, "%10.0f"), "DMY")
    27nov2014
    Last edited by Nick Cox; 28 Nov 2014, 06:13.

    Comment


    • #3
      I was going to suggest something slower but more readable:
      Nick's one-line solution is more elegant, though.

      Code:
      clear
      set obs 1
      gen x=27112014
      
      gen day = int(x/1000000)
      gen month = int(x/10000) - day*100
      gen year = x - month*10000 - day*1000000
      gen date = mdy(month, day, year)
      
      format date %dd_m_CY
      
      li

      Comment


      • #4
        todate from SSC remains accessible:

        Code:
         
        . gen x=27112014
        
        . todate x, gen(xdate) pattern(ddmmyyyy) 
        
        . l xdate in 1
        
             +-----------+
             |     xdate |
             |-----------|
          1. | 27nov2014 |
             +-----------+

        Comment

        Working...
        X