Announcement

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

  • How do I operate a dates variable to get a new variable that shows a difference in number of years

    This is probably out there but I have checked around to no avail. I have a dates variable and I want to generate a new date variable that is 20 years less. That is, for each date observation I generate a new variable with exactly 20 years back. Here is a MWE of the date var I have:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input long date
    43466
    43466
    42736
    42370
    43466
    43191
    42552
    42186
    42917
    41821
    42186
    43466
    43466
    43466
    42675
    43466
    43466
    43466
    43466
    43405
    end
    To convert to readable dates, I use
    Code:
    format date %td
    I get dates that are 60 years ahead. I want to get off the extra years and get a new var with correct dates.


  • #2
    Code:
    clear
    input long date
    43466
    43466
    42736
    42370
    43466
    43191
    42552
    42186
    42917
    41821
    42186
    43466
    43466
    43466
    42675
    43466
    43466
    43466
    43466
    43405
    end
    
    gen newdate= mdy(month(date), day(date), year(date)-60)
    format date newdate %td
    Res.:

    Code:
    . l, sep(0)
    
         +-----------------------+
         |      date     newdate |
         |-----------------------|
      1. | 02jan2079   02jan2019 |
      2. | 02jan2079   02jan2019 |
      3. | 02jan2077   02jan2017 |
      4. | 02jan2076   02jan2016 |
      5. | 02jan2079   02jan2019 |
      6. | 02apr2078   02apr2018 |
      7. | 02jul2076   02jul2016 |
      8. | 02jul2075   02jul2015 |
      9. | 02jul2077   02jul2017 |
     10. | 02jul2074   02jul2014 |
     11. | 02jul2075   02jul2015 |
     12. | 02jan2079   02jan2019 |
     13. | 02jan2079   02jan2019 |
     14. | 02jan2079   02jan2019 |
     15. | 02nov2076   02nov2016 |
     16. | 02jan2079   02jan2019 |
     17. | 02jan2079   02jan2019 |
     18. | 02jan2079   02jan2019 |
     19. | 02jan2079   02jan2019 |
     20. | 02nov2078   02nov2018 |
         +-----------------------+

    Comment


    • #3
      The usual twist is what about leap years when there was a 29 February? Note that 1920 was a leap year but 1900 wasn't. This probably won't bite you so long as you have the right month and day.


      Code:
      . di mdy(2, 29, 1920)
      -14551
      
      . di mdy(2, 29, 1920 - 20)
      .
      The bigger error evident in #1 was presumably importing from a source with daily date origin 1 January 1900. To adjust for that subtracting 60 years is not quite right as there was no 29 February 1900. The adjustment needed is the difference between mdy(1, 1, 1900) and mdy(1,1, 1960).
      Last edited by Nick Cox; 23 Feb 2021, 08:17.

      Comment


      • #4
        Thank you Nick and Andrew!

        Comment

        Working...
        X