How to Get First or Last Day of Month in R with lubridate and base R

code
rtip
timeseries
Author

Steven P. Sanderson II, MPH

Published

February 13, 2024

Introduction

When working with dates in R, you’ll often need to find the first or last day of the current month or any given month. There are a couple easy ways to do this using the lubridate package and base R functions. In this post, I’ll show you how.

Examples

Using lubridate

The lubridate package makes working with dates in R much easier. It has a number of helper functions for manipulating and extracting info from Date and POSIXct objects.

To get the first day of the current month, you can use floor_date() and pass it the current date:

library(lubridate)

today <- Sys.Date() # or Sys.time() for POSIXct
first_day <- floor_date(today, unit = "month")
first_day
[1] "2024-02-01"

This will return a Date object with the first day of the month.

To get the last day, use ceiling_date() instead:

last_day <- ceiling_date(today, unit = "month") - days(1)
last_day
[1] "2024-02-29"

You can also pass any Date object to these functions to get the first or last day of that month:

date <- ymd("2023-06-15")
floor_date(date, "month") # 2023-06-01
[1] "2023-06-01"
ceiling_date(date, "month") - days(1) # 2023-06-30
[1] "2023-06-30"

The lubridate functions make this really easy!

Base R Methods

You can also get the first and last day of month using just base R functions.

For the first day, use as.Date() with format() and pass it the year, month, and day 1:

first_day <- as.Date(format(today, "%Y-%m-01"))
first_day
[1] "2024-02-01"

For the last day, we can use 0 as the day which will give the last day of the month:

last_day <- as.Date((format(today + months(1), "%Y-%m-01")))-1
last_day
[1] "2024-02-29"

A bit more work than lubridate, but good to know you can do this with just base R.

I hope this helps you easily get the first and last day of the month in your own date analyses in R! Let me know if you have any other questions.