Announcement

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

  • Converting MDY to Y

    Hi all, I am having problems finding the right coding commands to convert a variable in my data set (deliverydate, which is in M,D,Y format) into a new variable (deliveryyear, which I want in Y format).

    Any suggestions?
    Last edited by Hannah Bacheller; 06 Oct 2019, 22:18.

  • #2
    In the future, when showing data examples, please use the -dataex- command to do so. If you are running version
    16 or a fully updated version 15.1 or 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc
    install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save
    you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data
    that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also
    makes it possible for those who want to help you to create a faithful representation of your example to try out their
    code, which in turn makes it more likely that their answer will actually work in your data.



    When asking for help with code, always show example data. When showing example data, always use -dataex-.

    Since you do not show example data, I can only guess what you mean by a variable being "in M, D, Y" format, as there is no such thing in Stata. Do you mean you have a string variable that looks like "October 6, 2019" or "10/6/2019" or "6/10/2019" or the like? Or do you mean you have an actual Stata internal format numeric date variable whose Stata display format is something along the lines of %tdNN_d,CCYY?

    If you have a string variable and the year is in the last four characters, then you can get what you want with
    Code:
    gen int deliveryyear = real(substr(deliverydate, -4, 4))
    If you have a real Stata internal format numeric date variable, then it's
    Code:
    gen int deliveryyear = year(deliverydate)
    Recommended reading: -help datetime- and click on the blue link near the top of the screen to go to the datetime variables section of the PDF manuals that come installed with your Stata.

    Comment


    • #3
      Thank you so much for your help and for your suggestions for edits in future posts/questions.

      I did mean I had a string variable, and the first code you suggested did the trick!

      Thanks again, you're a live saver!

      Comment

      Working...
      X