Dear R Help, I am trying to get fields showing the last day of each month for a monthly closing project. In order to find the last day of the previous month, I subtract the number of days from the current month. For all months my code works; however, for October, my code doesn't work...it returns 2010-09-*29* instead of 2010-09-*30*. format(strptime("2010-10-31", "%Y-%m-%d")-(as.numeric(format(as.Date("2010-10-31"),"%d"))*24*3600),"%Y-%m-%d") I appreciate any suggestions or tips. Thank you. Ben [[alternative HTML version deleted]]
Benjamin Williams <ben <at> bwmcct.com> writes:> I am trying to get fields showing the last day of each month for a monthly > closing project. In order to find the last day of the previous month, I > subtract the number of days from the current month. For all months my code > works; however, for October, my code doesn't work...it returns > 2010-09-*29* instead > of 2010-09-*30*. > > format(strptime("2010-10-31", > "%Y-%m-%d")-(as.numeric(format(as.Date("2010-10-31"),"%d"))*24*3600),"%Y-%m-%d") Very timely question. This is a daylight savings time issue; subtracting 24 hours gives a different answer when there are only 23 hours in a particular day ("spring forward, fall back"). Search the R-help archives for the last week or so for a similar issue. (Hint: try subtracting days from dates rather than converting to seconds first.) Ben Bolker
On Mon, Nov 8, 2010 at 7:06 AM, Benjamin Williams <ben at bwmcct.com> wrote:> Dear R Help, > > I am trying to get fields showing the last day of each month for a monthly > closing project. ?In order to find the last day of the previous month, I > subtract the number of days from the current month. For all months my code > works; however, for October, my code doesn't work...it returns > 2010-09-*29* instead > of 2010-09-*30*. > > format(strptime("2010-10-31", > "%Y-%m-%d")-(as.numeric(format(as.Date("2010-10-31"),"%d"))*24*3600),"%Y-%m-%d") >There are many ways to do this but here is one using as.yearmon in zoo. This converts the Date variable, today, to "yearmon" class which is a year and a fraction representing a month. Then it converts it back to "Date" class using frac = 1 which means all the way to the end of the month (frac = 0, the default, means 1st of month, etc.):> library(zoo) > today <- Sys.Date() > as.Date(as.yearmon(today), frac = 1)[1] "2010-11-30" If you are trying to show monthly data another option might be just to not show the day at all:> format(as.yearmon(today))[1] "Nov 2010"> > # or without yearmon > format(today, "%b %Y")[1] "Nov 2010" -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com