Announcement

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

  • How to convert date variable to year group?

    I am given a list of date variables in dd/mm/yy and I would like to sort the variables out in the form of grouping them together by the specific year. For example, I want all date variables of 2010 to be in 2010 year variable and all date variables of 2011 to be in 2011 year variable.

    How do I go about doing this?
    Last edited by Goh jedrek; 31 May 2021, 09:46.

  • #2
    Two pieces of advice to begin with.

    First, Stata's "date and time" variables are complicated and there is a lot to learn. If you have not already read the very detailed Chapter 24 (Working with dates and times) of the Stata User's Guide PDF, do so now. If you have, it's time for a refresher. After that, the help datetime documentation will usually be enough to point the way. You can't remember everything; even the most experienced users end up referring to the help datetime documentation or back to the manual for details. But at least you will get a good understanding of the basics and the underlying principles. An investment of time that will be amply repaid.

    All Stata manuals are included as PDFs in the Stata installation (since version 11) and are accessible from within Stata - for example, through the PDF Documentation section of Stata's Help menu.

    Second, this would be a better answer if the question had been better presented. Your question really isn't clear without more detail, and I have had to guess at a good answer from what you have shared. In the future please help us help you by showing example data. The Statalist FAQ provides advice on effectively posing your questions, posting data, and sharing Stata output.

    Perhaps the following example will help you convert dates that appear as a string into Stata Internal Format dates (as described in the recommended reading) that can be used in Stata calculations and analyses.
    Code:
    input str12 sample
    "5/31/21"
    "6/1/21"
    "6/1/25"
    "6/1/26"
    "1/1/99"
    "11/10/50"
    end
    generate date = daily(sample,"MDY",2025)
    format %td date
    generate year = yofd(date)
    list, clean
    Code:
     input str12 sample
    
               sample
      1. "5/31/21"
      2. "6/1/21"
      3. "6/1/25"
      4. "6/1/26"
      5. "1/1/99"
      6. "11/10/50"
      7. end
    
    . generate date = daily(sample,"MDY",2025)
    
    . format %td date
    
    . generate year = yofd(date)
    
    . list, clean
    
             sample        date   year  
      1.    5/31/21   31may2021   2021  
      2.     6/1/21   01jun2021   2021  
      3.     6/1/25   01jun2025   2025  
      4.     6/1/26   01jun1926   1926  
      5.     1/1/99   01jan1999   1999  
      6.   11/10/50   10nov1950   1950  
    
    .

    Comment

    Working...
    X