[R] Number of Days Between Dates: Incorrect Results For Date Calucations.

Gabor Grothendieck ggrothendieck at gmail.com
Tue Feb 21 17:08:08 CET 2006


The results are actually correct if you consider daylight savings time.

For example, try this and note that the difference is 23 hours, not 24 hours:

   as.POSIXct("2004-04-05") - as.POSIXct("2004-04-04")

You can address this by either using Date or chron classes or adding
the tz = "GMT" argument on your as.POSIXct calls as GMT does not
have daylight savings time.

See the Help Desk article in R News 4/1 for more on this.


On 2/21/06, gerald.herbert at hubbardbreeders.com
<gerald.herbert at hubbardbreeders.com> wrote:
> In some cases, incorrect results are produced by the code below intended to
> calculate the number of days between 2 dates.  The year in question was a
> leap year.
>
> Note the results for 2004-04-04 and 2004-04-05 are the same! They should be
> 37 and 38 respectively.
>
> > as.integer(as.POSIXct("2004-04-02") - as.POSIXct("2004-02-27"))
> [1] 35
> > as.integer(as.POSIXct("2004-04-03") - as.POSIXct("2004-02-27"))
> [1] 36
> > as.integer(as.POSIXct("2004-04-04") - as.POSIXct("2004-02-27"))
> [1] 37
> > as.integer(as.POSIXct("2004-04-05") - as.POSIXct("2004-02-27"))
> [1] 37
> > as.integer(as.POSIXct("2004-04-06") - as.POSIXct("2004-02-27"))
> [1] 38
>
>
>
> > as.integer(difftime(as.POSIXct("2004-04-06"),
> as.POSIXct("2004-02-27"),units="days"))
> [1] 38
> > as.integer(difftime(as.POSIXct("2004-04-04"),
> as.POSIXct("2004-02-27"),units="days"))
> [1] 37
> > as.integer(difftime(as.POSIXct("2004-04-05"),
> as.POSIXct("2004-02-27"),units="days"))
> [1] 37
>
> It appears that difftime() and "-" are producing invalid results.
>
>
> Regards,
>
> Gerald Herbert
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list