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

  • by
lubridate-floor-ceiling
Want to do a random act of kindness? Share this post.

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')

Now you can use start_date and end_date wherever you want.

Great success!

Want to do a random act of kindness? Share this post.