更改日期的打印格式而不将其转换为字符 [英] Change print format of a Date without converting it to character

查看:39
本文介绍了更改日期的打印格式而不将其转换为字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With a Date object in R, is it possible to choose a different print format than the default "%Y-%m-%d" while keeping its Date class? The format() function converts it back to a character string.

# 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的子类,但可能不值得.

You can create a subclass of Date with its own print method but its probably not worth it.

如果使用chron,则可以将格式与每个对象相关联:

If you use chron then you can associate a format with each object:

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

这篇关于更改日期的打印格式而不将其转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆