5

I have a question similar to Round a POSIX date (POSIXct) with base R functionality, but I'm hoping to always round the date up to midnight the next day (00:00:00).

Basically, I want a function equivalent to ceiling for POSIX-formatted dates. As with the related question, I'm writing my own package, and I already have several package dependencies so I don't want to add more. Is there a simple way to do this in base R?

Community
  • 1
  • 1
Eli Sander
  • 1,228
  • 1
  • 13
  • 29
  • You're going to have issues with timezones and daylight saving time. Just use `Date` if you don't need the time component. – Joshua Ulrich Aug 09 '12 at 17:52
  • I'm web scraping POSIXct-style timestamps, and I'm trying to round them to the next day. I don't know if the `Date` format would work for that... – Eli Sander Aug 09 '12 at 18:08
  • So you have POSIXct-style character strings... can't you just strip the time component from the string, convert to `Date` and add 1 to the result? – Joshua Ulrich Aug 09 '12 at 18:11
  • I'm actually getting UNIX-style timestamps, which are in nanoseconds. So I was going to strip the nanoseconds and convert to POSIXct, then work with them from there. – Eli Sander Aug 09 '12 at 18:12
  • It would be useful if you could provide an example of your input (including timezone, if applicable), how you're converting it to POSIXct, and the desired output (including timezone, if applicable). – Joshua Ulrich Aug 09 '12 at 18:33

2 Answers2

9

Maybe

trunc(x,"days") + 60*60*24

> x <- as.POSIXct(Sys.time())
> x
[1] "2012-08-09 18:40:08 BST"
> trunc(x,"days")+ 60*60*24
[1] "2012-08-10 BST"
shhhhimhuntingrabbits
  • 7,397
  • 2
  • 23
  • 23
0

A quick and dirty method is to convert to a Date (which truncates the time), add 1 (which is a day for Date) and then convert back to POSIX to be at midnight UTC on the next day. As @Joshua Ulrich points out, timezone/daylight savings issues may give results you don't expect:

as.POSIXct(as.Date(Sys.time())+1)
[1] "2012-08-10 01:00:00 BST"
James
  • 65,548
  • 14
  • 155
  • 193