Instead of directly doing the -
, use difftime
with units
which will have more control on the output units i.e. if we convert it to sec
onds, then we can use the seconds_to_period
from lubridate
and then extract the various components to create the format
as in expected output
library(lubridate)
out <- seconds_to_period(difftime(time_3, time_2, units = 'sec'))
sprintf('%02d:%02d', out@hour, second(out))
sprintf('%02d:%02d:%02d', out@hour, out@minute, second(out))
sprintf('%02d:%02d', out@minute, second(out))
If there are more than one object, we can create a function for reuse
f1 <- function(time1, time2, format = "HH:MM") {
tmp <- lubridate::seconds_to_period(difftime(time2, time1, units = 'sec'))
switch(format,
"HH:MM" = sprintf('%02d:%02d', tmp@hour, second(tmp)),
"HH:MM:SS" = sprintf('%02d:%02d:%02d', tmp@hour,
tmp@minute, second(tmp)),
"MM:SS" = sprintf('%02d:%02d', tmp@minute,
second(tmp)))
}
-testing
> f1(time_2, time_3)
[1] "02:09"
> f1(time_2, time_3, format = "HH:MM:SS")
[1] "02:13:09"
> f1(time_2, time_3, format = "MM:SS")
[1] "13:09"