rposixct

R Day Difference is Fraction (Bug or Feature?)


it's a little surprising that the difference between two days ends up as a fraction, presumably because of some posix magic about seconds. alas, in this case, what is the recommended way to obtain the day difference? just add a little and convert to integer?

mydates <- c( as.POSIXct("2010-03-29") , as.POSIXct("2000-01-21") )
> mydates[1] - mydates[2]
Time difference of 3720 days
> as.numeric(mydates[1] - mydates[2])
[1] 3720
> (as.numeric(mydates[1] - mydates[2])) - 3720
[1] -0.04167

Solution

  • You can use timezone argument tz in as.POSIXct() and use the difftime() with the units argument set to "days" to avoid possible daylight saving time (DST) like this

    date1 <- as.POSIXct("2010-03-29", tz = "UTC")
    date2 <- as.POSIXct("2000-01-21", tz = "UTC")
    
    day_difference <- difftime(date1, date2, units = "days")