I guess the title says it all: I have a pair of POSIX time objects produced with Sys.time()
and I want the difference displayed in a consistent manner. I expect
The subject and content of the post ask for different formats so we will assume that the one in the body of the post is desired, i.e. DD:HH:MM:SS .
Assuming the input, x
, must be a vector of seconds or a difftime object:
Fmt <- function(x) UseMethod("Fmt")
Fmt.difftime <- function(x) {
units(x) <- "secs"
x <- unclass(x)
NextMethod()
}
Fmt.default <- function(x) {
y <- abs(x)
sprintf("%s%02d:%02d:%02d:%02d",
ifelse(x < 0, "-", ""), # sign
y %/% 86400, # days
y %% 86400 %/% 3600, # hours
y %% 3600 %/% 60, # minutes
y %% 60 %/% 1) # seconds
}
# test
now <- Sys.time()
now100 <- now + 100
Fmt(now100 - now)
## [1] "00:00:01:40"
Fmt(now - now100)
## "-00:00:01:40"