Announcement

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

  • Number of days in a month

    Hello,

    I have a very simple question. Is there a way or a function to extract the number of days of a particular month? for example if I have a date such 1/02/2021 (european format) the answer should be 29

    KR

  • #2
    The one thing that you know is that every month starts on the 1st. So, the last day of the previous month is the first day of the current month minus 1. See https://journals.sagepub.com/doi/abs...36867X19874247. Exploiting this

    Code:
    di (td(01mar2021) - 1) - td(01feb2021) + 1
    Res.:

    Code:
      di (td(01mar2021) - 1) - td(01feb2021) + 1
    28

    So, February 2021 had 28 days and not 29!

    Comment


    • #3
      Otherwise put length of current month = day(date of last day of current month) = day(date of first day of next month - 1) = ...


      Code:
      . di day(dofm(1 + mofd(mdy(3, 25, 2021))) - 1)
      31

      Comment


      • #4
        Many thanks to both Andrew and Nick, it worked perfectly

        Comment


        • #5
          Hi,

          I have a follow up question: I have a daily dataset which runs over several years and want to extract the number of days per month for each month and store it in a new variable noofdays. Do I have to loop over all years and month or is there a more elegant way to do so?

          Thanks in advance!

          Comment


          • #6
            No loop needed. The function daysinmonth() yields precisely this. There is no data example in #5, so here is a token:

            Code:
            clear 
            set obs 3 
            gen ddate = mdy(12, 25, 2022) in 1
            replace ddate = mdy(2, 15, 2022) in 2 
            replace ddate = mdy(6, 19, 2023) in 3
            format ddate %td 
            
            gen wanted = daysinmonth(ddate)
            
            list 
            
                 +--------------------+
                 |     ddate   wanted |
                 |--------------------|
              1. | 25dec2022       31 |
              2. | 15feb2022       28 |
              3. | 19jun2023       30 |
                 +--------------------+

            Comment


            • #7
              Thanks!

              Comment

              Working...
              X