Home » Get the first day or the last day of the month in R using Lubridate

Get the first day or the last day of the month in R using Lubridate

Sometimes I create reports or analyses that I would like to run on a monthly base. It saves some time if I can simply let the report run, without you having to edit any variables. Lubridate has two really cool functions to get the first day or the last day of a particular month.

These functions are floor_date() and ceiling_date(). When you give them a date, you can have these functions return the lowest or highest possible, month, week or day.

floor_date(ymd('2019-05-12'), 'month') # returns '2019-05-01'

To get the first day and the last day of the month that has passed, we can do the following. We subtract 1 month from the current date and use the functions I described earlier.

start_date <- floor_date(Sys.Date() %m-% months(1), 'month')
end_date <- ceiling_date(Sys.Date() %m-% months(1), 'month') %m-% days(1)

Now you can use start_date and end_date wherever you want.

By the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. Hope it helps!

Great success!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

5 thoughts on “Get the first day or the last day of the month in R using Lubridate”

  1. i get 2020-09-01 as ceiling_date(Sys.Date()%m-% months(1), ‘month’) for today Sept 4 subtracting 1 gives the last day of August. R4.0.0.

    1. Hi Vincent, thanks for reaching out.
      Indeed, there was a mistake in the blog post.
      ceiling_date(Sys.Date() %m-% months(1), ‘month’) %m-% days(1) is the correct answer.
      Best regards
      Roel

  2. Isn’t

    “`r
    start_date <- floor_date(today(), 'month') – months(1)
    end_date <- floor_date(today(), 'month') – days(1)
    “`

    shorter and always gives the same result?

Leave a Reply

Your email address will not be published. Required fields are marked *