Home > other >  Interval of two dates not output correctly in R
Interval of two dates not output correctly in R

Time:09-10

Wanted to get the interval between 2 days displayed in days. Using lubridate package. Method 1 using interval function.

library(lubridate)
date1 <- as.Date("2022-08-08")
date2 <- as.Date("2022-09-08")
x <- interval(date1, date2)
print(x)
days(x)

Output as follows

[1] 2022-08-08 UTC--2022-09-08 UTC
[1] "2678400d 0H 0M 0S"

Question: Why the answer is not correct? 2678400 days!

Method 2 using difftime function.

y <- difftime(date1, date2, units="days")
print(y)

Output as follows

Time difference of 31 days

The thing is, I want it to display only 31 instead of the whole sentence "Time difference of 31 days" Need some guidance here.

CodePudding user response:

lubridate::days() works with numerics. You've given it a period. as.numeric(x) gives 2678400 (the number of seconds between 2022-08-08 and 2022-09-08?). You're a victim of implicit coercion.

@jay.sf has given you the solution for difftime. To get the correct answer using lubridate:

time_length(x, "days")
[1] 31

@JustJames gave the full explanation of what went wrong in their now-deleted answer:

"According to the docs

as.interval changes difftime, Duration, Period and numeric class objects to intervals that begin at the specified date-time. Numeric objects are first coerced to timespans equal to the numeric value in seconds."

CodePudding user response:

Try this,

date1 <- as.Date("2022-08-08")
date2 <- as.Date("2022-09-08")

dateDiff <- as.numeric(difftime(date2, date1))
print(dateDiff)

Output

> dateDiff = as.numeric(difftime(date2, date1))
> print(dateDiff)
[1] 31

Hope this helps!

  • Related