Announcement

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

  • converting string (MDY) to date?

    Hi,

    I know there are SO many questions regarding this, but I just cannot get this to work. I am using Stata 18.

    Code:
     
     clear set obs 1 gen date_str = "feb102024"
    How would I convert feb102024 to date? Or any variation of MDY, for instance, February 20, 2024?

    Also, is a string is like below
    Code:
     
     clear set obs 1 gen date_str_1 = "feb10-24, 2024" gen date_str_2 = "feb10-mar10, 2024"
    Is there an easy way to calculate the date interval? Or am I to just use split and such commands?

    Thank you so much!

    This is crossposted here:
    https://www.reddit.com/r/stata/comme...tring_to_date/

  • #2
    How would I convert feb102024 to date? Or any variation of MDY, for instance, February 20, 2024?
    Use the -daily()- function:
    Code:
    . display daily("feb102024", "MDY")
    23416
    
    . display %td 23416
    10feb2024
    Is there an easy way to calculate the date interval? Or am I to just use split and such commands?
    No easy way. You will need to split. Even then, this is going to be a real bear. The problem is that while natural human languages have no difficulty filling in the gaps in an expression like "feb10-24, 2024" and interpreting it as the interval between 10FEB2024 and 24FEB2024, this will be a struggle in Stata (or any other statistical language I'm familiar with). If all of the expressions you are concerned with had the same structure, it wouldn't be too bad. But when sometimes you gap just the year, and other times you gap the month and year, this is going to be a challenge. You will have to write separate code for each of these cases. Hopefully in your real use cases you can at least rely on the consistent use of - to separate days (if the month is gapped) or day-months (if not), and comma to separate the year.

    By the way, the system local macro `c(Mons)' will be helpful with converting the three-letter month abbreviations to numbers 1-12.
    Code:
    gen n_month = (strpos("`c(Mons)'", str_month) + 3)/4
    Last edited by Clyde Schechter; 01 Feb 2024, 12:52.

    Comment


    • #3
      @Clyde Schechter

      Thank you very much!

      Comment

      Working...
      X