Announcement

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

  • How to substract 1 year from a ddmmyyyy variable

    Dear statalist,

    I have some dates, such as 05sep2014, in %td format, and I would like to create the same date in the previous year, so in this case, 05sep2013, how to do this? Thanks.

  • #2
    Code:
    clear
    input x1
    19971
    end
    format x1 %td
    
    gen x2 = mdy(month(x1), day(x1), year(x1)-1)
    format x2 %td
    
    list
    Results:
    Code:
         +-----------------------+
         |        x1          x2 |
         |-----------------------|
      1. | 05sep2014   05sep2013 |
         +-----------------------+

    Comment


    • #3
      There is no "same date in the previous year" when the date is a leap year day. You have to make a choice.
      Code:
      clear
      input x1
      19971
      21940
      21974
      21975
      21985
      end
      format x1 %td
      
      gen x2 = mdy(month(x1), day(x1), year(x1)-1)
      format x2 %td
      
      gen x3f = mdy(month(x1), day(x1), year(x1)-1)
      replace x3f = mdy(month(x1), day(x1-1), year(x1)-1) if missing(x3f)
      
      gen x3m = mdy(month(x1), day(x1), year(x1)-1)
      replace x3m = mdy(month(x1)+1,1, year(x1)-1) if missing(x3m)
      
      format x3f x3m %td
      
      list
      Code:
      . list
      
           +-----------------------------------------------+
           |        x1          x2         x3f         x3m |
           |-----------------------------------------------|
        1. | 05sep2014   05sep2013   05sep2013   05sep2013 |
        2. | 26jan2020   26jan2019   26jan2019   26jan2019 |
        3. | 29feb2020           .   28feb2019   01mar2019 |
        4. | 01mar2020   01mar2019   01mar2019   01mar2019 |
        5. | 11mar2020   11mar2019   11mar2019   11mar2019 |
           +-----------------------------------------------+
      Last edited by William Lisowski; 01 Dec 2022, 16:29.

      Comment


      • #4
        Hi Ken and William,

        Thank you both for the kind help!

        Comment

        Working...
        X