This is what I mean by super-classing it:
format.myPOSIX <- function(x, tz = "", usetz = FALSE, ...) {
dots <- list(...)
fmt <- NA
if ("format" %in% names(dots)) {
fmt <- dots$format
dots$format <- NULL
}
if (inherits(x, "Date")) {
if (is.na(fmt)) fmt <- "%m/%d/%Y"
func <- match.fun("format.Date")
} else { # POSIXt
if (is.na(fmt)) fmt <- "%m/%d/%Y %H:%M:%S"
func <- match.fun("format.POSIXct")
}
do.call(func, c(list(x, tz = tz, usetz = usetz), format = fmt, dots))
}
print.myPOSIX <- function(x, tz = "", usetz = FALSE, ...) {
print(format.myPOSIX(x, tz = tz, usetz = usetz))
}
Example, since your data is not available.
set.seed(42)
datevec <- sort(Sys.Date() + sample(20, size=3))
class(datevec) <- c("myPOSIX", class(datevec))
datevec
# [1] "10/23/2021" "10/27/2021" "11/08/2021"
diff(datevec)
# Time differences in days
# [1] 4 12
psxvec <- sort(Sys.time() + sample(2000, size=3))
class(psxvec) <- c("myPOSIX", class(psxvec))
psxvec
# [1] "10/22/2021 09:55:28" "10/22/2021 09:56:47" "10/22/2021 09:58:02"
diff(psxvec)
# Time differences in mins
# [1] 1.316667 1.250000
showing that the printed format is "%m/%d/%Y"
yet numeric operations still function.
This should also work in data.frame
and similar structures:
data.frame(dt = datevec, psx = psxvec)
# dt psx
# 1 10/23/2021 10/22/2021 09:58:02
# 2 10/27/2021 10/22/2021 09:59:21
# 3 11/08/2021 10/22/2021 10:00:36
tibble::tibble(dt = datevec, psx = psxvec)
# # A tibble: 3 x 2
# dt psx
# <date> <dttm>
# 1 2021-10-23 2021-10-22 09:58:02
# 2 2021-10-27 2021-10-22 09:59:21
# 3 2021-11-08 2021-10-22 10:00:36
data.table::data.table(dt = datevec, psx = psxvec)
# dt psx
# <myPOSIX> <myPOSIX>
# 1: 10/23/2021 10/22/2021 09:58:02
# 2: 10/27/2021 10/22/2021 09:59:21
# 3: 11/08/2021 10/22/2021 10:00:36