Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert difftime time to years, months and days

Tags:

r

How can I accurately convert the products (units is in days) of the difftime below to years, months and days?

difftime(Sys.time(),"1931-04-10")
difftime(Sys.time(),"2012-04-10")

This does years and days but how could I include months?

yd.conv<-function(days, print=TRUE){
    x<-days*0.00273790700698851
    x2<-floor(x)
    x3<-x-x2
    x4<-floor(x3*365.25)
    if (print) cat(x2,"years &",x4,"days\n")
    invisible(c(x2, x4))
}

yd.conv(difftime(Sys.time(),"1931-04-10"))
yd.conv(difftime(Sys.time(),"2012-04-10"))

I'm not sure how to even define months either. Would 4 weeks be considered a month or the passing of the same month day. So for the later definition of a month if the initial date was 2012-01-10 and the current 2012-05-31 then we'd have 0 years, 5 months and 21 days. This works well but what if the original date was on the 31st of the month and the end date was on feb 28 would this be considered a month?

As I wrote this question the question itself evolved so I'd better clarify:

What would be the best (most logical approach) to defining months and then how to find diff time in years, months and days?

like image 479
Tyler Rinker Avatar asked May 31 '12 15:05

Tyler Rinker


Video Answer


1 Answers

If you're doing something like

difftime(Sys.time(), someDate)

It comes as implied that you must know what someDate is. In that case, you can convert this to a POSIXct class object that gives you the ability to extract temporal information directly (package chron offers more methods, too). For instance

as.POSIXct(c(difftime(Sys.time(), someDate, units = "sec")), origin = someDate)

This will return your desired date object. If you have a timezone tz to feed into difftime, you can also pass that directly to the tz parameter in as.POSIXct.

Now that you have your date object, you can run things like months(.) and if you have chron you can do years(.) and days(.) (returns ordered factor).

From here, you could do more simple math on the difference of years, months, and days separately (converting to appropriate numeric representations). Of course, convert someDate to POSIXct will be required.

EDIT: On second thought, months(.) returns a character representation of the month, so that may not be efficient. At least, it'll require a little processing (not too difficult) to give a numeric representation.

like image 166
Bryan Goodrich Avatar answered Nov 13 '22 08:11

Bryan Goodrich