更改日期的打印格式而不将其转换为字符

Change print format of a Date without converting it to character

对于 R 中的 Date 对象,是否可以选择与默认 "%Y-%m-%d" 不同的打印格式,同时保持其 Date 类? format() 函数将其转换回 character 字符串。

# I start with a character string and convert it to a date
date_char <- "01-05-2015"
date <- as.Date(date_char, format = "%d-%m-%Y")

# By default, R re-formats the date as "%Y-%m-%d"
date
# [1] "2015-05-01"

# I want to keep the Date class, but with the original format
# format() converts it back to a character variable
str(format(date, "%d-%m-%Y"))
# chr "01-05-2015"

您可以使用自己的打印方法创建 Date 的子类,但这可能不值得。

如果您使用 chron,那么您可以为每个对象关联一个格式:

library(chron)

c1 <- chron(c("02/27/92", "02/27/92", "01/14/92")); c1
## [1] 02/27/92 02/27/92 01/14/92

c2 <- chron(c("02/27/92", "02/27/92", "01/14/92"), out.format = "y-mmm-d"); c2
## [1] 1992-Feb-27 1992-Feb-27 1992-Jan-14