Is there any easy way for getting start date and end date of previous month from the current date in R?
I have only the current date. From it, i want to get the prev
Using lubridate
it's a piece of cake:
library(lubridate)
floor_date(Sys.Date() - months(1), "month")
There is a plenty of good libraries in R. Seems like everything you need is already created.
UPDATED version:
library(lubridate)
floor_date(as.Date("2011-03-29"), "month") - months(1)
This one is corrected to work well with the 29th of march.
Previous Month Start Date:
format(Sys.Date() - 30, '%Y-%m-01')
Previous Month End Date:
as.Date(format(Sys.Date(), '%Y-%m-01')) - 1
Another option with lubridate package is to use the rollback function, that as the description says, do exactly that.
rollback changes a date to the last day of the previous month or to the first day of the month. Optionally, the new date can retain the same hour, minute, and second information.
library(lubridate)
currentDate <- Sys.Date()
end_last_month <- rollback(currentDate)
init_last_month <- rollback(end_last_month, roll_to_first = TRUE)
A number of packages have handy date functions, but to roll your own:
A start of month function:
som <- function(x) {
as.Date(format(x, "%Y-%m-01"))
}
and an end of month function (although you won't need this here):
eom <- function(x) {
som(som(x) + 35) - 1
}
That should get you going. For example, to get the end of the previous month:
som(Sys.Date()) - 1
[1] "2012-10-31"
and the start of the month:
som(som(Sys.Date()) - 1)
[1] "2012-10-01"
use timeperiodsR
for get start and end date of any period.
# install.packages("timeperiodsR")
timeperiodsR::previous_month()
You can use the library lubridate
, which is very good at doing date arithmetic.
library(lubridate)
currentDate <-Sys.Date()
# end of previous month:
eopm <- currentDate - days(day(currentDate))
# [1] "2012-10-31"
# start of previous month:
sopm <- currentDate - days(day(currentDate))
sopm <- sopm - days(day(sopm) - 1)
# [1] "2012-10-01"