Announcement

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

  • Converting to a date from YMD

    Hello everyone,




    I have a data set with the variable date in it and it looks like this


    Code:
    date
    
    19990106
    
    20000425
    
    19990930
    
    ...


    it is in this format currently:

    Code:
                             storage                     display     value
              variable       name   type          format     label      variable label 
              date            long    %12.0g


    How can I convert it to a normal date, so I can substract other dates from it? Because I have a second date variable in this format, which I think should be correct?: (And it looks like 13sept1999 in the editor)


    Code:
                                             storage            display    value
                    variable            name   type    format     label      variable label
                     event_date      int     %td                                      event_date


    I tried the following but I got an error:

    Code:
     . gen edate2 = date(date, "ymd")
     type mismatch r(109);


    I'd be really thankful for any ideas, Thanks!
    Last edited by Stephan Molekski; 02 Jun 2019, 06:06.

  • #2
    Look at the help for date() which starts

    Code:
    date(s1,s2[,Y])
           Description:  the e_d date (days since 01jan1960) corresponding to s1 based on s2 and Y
    
                         s1 contains the date, recorded as a string, in virtually any format.
    So date() expects a string and you are feeding it a numeric variable: hence the error message, which should not be surprising.

    This will work, but note further that you need YMD as argument not ymd:

    Code:
    clear 
    input long date
    19990106
    20000425
    19990930
    end 
    
    
    gen wanted = daily(string(date, "%8.0f"), "YMD") 
    format date %8.0f 
    format wanted %td 
    
    list 
    
         +----------------------+
         |     date      wanted |
         |----------------------|
      1. | 19990106   06jan1999 |
      2. | 20000425   25apr2000 |
      3. | 19990930   30sep1999 |
         +----------------------+

    Comment


    • #3
      Cross-posted at https://www.reddit.com/r/stata/comme...date_from_ymd/

      Please note our policy on cross-posting, which is that you are asked to tell us about it. https://www.statalist.org/forums/help#crossposting

      Comment

      Working...
      X