Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting previous month start date and end date from current date in R

Tags:

date

r

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 previous month, start date of previous month, end date of previous month.

currentDate<-Sys.Date() #return today's date as "2012-11-07" 

I want the previous month start date as 2012-10-01 and end date as 2012-10-31 from today's date.

like image 856
Nandu Avatar asked Nov 07 '12 11:11

Nandu


People also ask

How do I get previous month in R?

The first date of the month in R 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. The last day of the previous month can be calculated with the rollback function from the lubridate package.

Is there a date data type in R?

In addition to the time data types R also has a date data type. The difference is that the date data type keeps track of numbers of days rather than seconds. You can cast a string into a date type using the as. Date function.

How do I get the year from a date in R?

To get the year from a date in R you can use the functions as. POSIXct() and format() . For example, here's how to extract the year from a date: 1) date <- as. POSIXct("02/03/2014 10:41:00", format = "%m/%d/%Y %H:%M:%S) , and 2) format(date, format="%Y") .


1 Answers

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" 
like image 176
seancarmody Avatar answered Sep 18 '22 21:09

seancarmody