Announcement

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

  • Converting dates to numeric variables

    Dear Stata folks,
    I have a need to convert Stata dates (currently in %td format) to numeric variables showing year and month YYYYMM. I don't seem to find a way, so any help is very much appreciated.

    -Marika

  • #2
    I'm not entirely sure what you mean, but I think this will do what you want:

    Code:
    gen int new_monthly_date = mofd(date_variable_I_already_have)
    format new_monthly_date %td
    If you use date and time variables with any frequency in your work, it is well worth your time and effort to study the Date and time functions section of the [FN] manual.

    Comment


    • #3
      Clyde: Typo: the format should be %tm, because what you create is a monthly date variable.

      Comment


      • #4
        Sorry for being unclear. I have Stata date variables but now the dates (at the precision of a month) need to be taken to another program in the form YYYYMM (year and month).
        For instance I need to convert
        15apr1985 to 198504
        15jan1999 to 199901
        15dec2004 to 200412
        etc.

        Comment


        • #5
          Nick Cox Thanks for picking that up. Yes, I meant %tm.

          Marika Jalovaara So this is a little different:

          Code:
          gen int year = yofd(date_variable_I_already_have)
          gen int month = mofd(date_variable_I_already_have)
          gen long variable_for_other_program = 100*year + month

          Comment


          • #6
            Thank you Clyde! That one was the answer. All I had to do is replace the "mofd" with "month".
            Last edited by Marika Jalovaara; 19 Feb 2016, 10:52.

            Comment


            • #7
              Marika, you are right. My mofd() was an error, and month() was correct. Glad you figured it out despite my mistake.

              Comment


              • #8
                You could do it in one line, interesting for anyone paid according to the reciprocal of the number of lines they write.

                Code:
                . di real(string(mofd(daily("15apr1985", "DMY")), "%tmCYN"))
                198504
                I think that translates to

                Code:
                gen variable_for_other_program = real(string(mofd(date_variable_I_already_have), "%tmCYN"))

                Comment

                Working...
                X