Announcement

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

  • Working with dates. Converting to stata date

    My date variable is of the form
    Code:
    date
    20010131
    20010131
    20010131
    20010131
    I want to convert it to Stata form that is something like 31Jan2001. So I can create month variables and year variables like m=month(date), y=year(date)

    So I tried to convert it using generate
    Code:
    statadate=date(date,"YMD")
    But it doesnt seem to work. Gives me an error saying type mismatch.

  • #2
    Delete seem to for the reason you report. date() expects a string argument.

    This works

    Code:
    . di %td daily("20010131", "YMD")
    31jan2001
    so you need

    Code:
    gen wanted = daily(strofreal(date, "%8.0f"), "YMD")
    format wanted %td
    where daily() is equivalent to date() (and a better name, in my view).

    Comment


    • #3
      It works Nick. Thanks a lot!
      I tried doing something after understanding the problem. The variable was long type. So I first converted it to string, and then went about business. Jotting down my code as well since its a little step by step and easier for a beginner to understand incase they stumble upon it.

      Code:
      tostring date, format(%10.0f) replace
      gen dt = date(date, "YMD")
      format dt %td
      
      gen mn=month(dt)
      gen yr=year(dt)

      Comment


      • #4
        It's almost the same thing. I wrote tostring myself-- now an official command -- because there was a request for the inverse to destring, but if you know what you want you can just use strofreal(). tostring is at heart a wrapper for strofreal().

        Comment

        Working...
        X