# Last or first date of the month in R

Here is probably the easiest way how to get the last or first date of the month that might be helpful in further calculations in R. You will need a lubridate package.

### The first date of the month in R

You can do it with the floor_date function from lubridate.

```Sys.Date()
#[1] "2020-12-14"

lubridate::floor_date(Sys.Date(), unit = "month")
#[1] "2020-12-01"```

If you have the first date of the month, then it is easy to calculate the last day of the previous month by simple subtraction, but it will work with the class of Date.

```lubridate::floor_date(Sys.Date(), unit = "month") - 1
#[1] "2020-11-30"```

The last day of the previous month can be calculated with the rollback function from the lubridate package.

```lubridate::rollback(Sys.Date())
#[1] "2020-11-30"```

### The last date of the month in R

You can do it with the ceiling_date function from lubridate.
If you use it by itself, then you will get the first date of next month.

```lubridate::ceiling_date(Sys.Date(), "month")
#[1] "2021-01-01"```

With simple subtraction, you can gate the last date of a given month.

```lubridate::ceiling_date(Sys.Date(), "month") - 1
#[1] "2020-12-31"```

### Generate a sequence of dates in R

By getting the necessary dates, you can generate a sequence of dates.

```seq(
from = floor_date(Sys.Date(), unit = "month"),
to = ceiling_date(Sys.Date(), "month") - 1,
by = "days"
)

# [1] "2020-12-01" "2020-12-02" "2020-12-03" "2020-12-04" "2020-12-05" "2020-12-06" "2020-12-07"
# [8] "2020-12-08" "2020-12-09" "2020-12-10" "2020-12-11" "2020-12-12" "2020-12-13" "2020-12-14"
#[15] "2020-12-15" "2020-12-16" "2020-12-17" "2020-12-18" "2020-12-19" "2020-12-20" "2020-12-21"
#[22] "2020-12-22" "2020-12-23" "2020-12-24" "2020-12-25" "2020-12-26" "2020-12-27" "2020-12-28"
#[29] "2020-12-29" "2020-12-30" "2020-12-31"```

Check out for more: How to generate time intervals or date sequence in R.

Posted

in