【问题标题】:Add one year to a posix time [duplicate]将一年添加到posix时间[重复]
【发布时间】:2016-05-05 22:30:32
【问题描述】:

我有一个类似 "2016-01-01" (YYYY-MM-DD) 的日期,我使用 as.numeric(as.POSIXct(...)) 将其用作整数。

我的问题是,有没有办法在这个日期添加一年、一个月或一天? 我的意思是,如果我在 2016 年添加一年,它与在 2015 年添加一年是不同的(双色的东西)。

1 月 1 日加 32 天与 2 月 1 日加 32 天不同(因为天数可能会改变)

我设法拥有可以使用数年和数月的东西,但我也想实现 days

how_long_is_simul <- function(lst){
    # Format DATE_START
    greg_date = intDate_to_gregorianDate(DATE_START)
    reg = "^([0-9]{4})\\-([0-9]{2})\\-([0-9]{2})$" # black-magic
    splited_date = str_match(greg_date, reg)

    # Manage months limit
    lst$years = lst$years + floor(lst$months/12)
    lst$months = lst$months%%12

    # Build new date
    my_vector = c(lst$years, lst$months, 0)
    end_date = paste(as.numeric(splited_date[2:4]) + my_vector, collapse = "-")
    return(round((gregorianDate_to_intDate(end_date)-DATE_START)/86400))
}

# AND the vars used by the function
DATE_START <- 1451606400 # 2016-01-01 GMT
lst   = list( # no days, because of bissextile years
    years  = 1,
    months = 0
)

基本上我所做的是从DATE_START 整数将其转换为公历,然后添加来自lst 的月/年,然后重建一个干净的字符串并将其重新转换为整数。

注意转换 int gregorian 是用 POSIXct 完成的

我不确定我是否解释得很好,但还是谢谢你:)

【问题讨论】:

标签: r date posixct


【解决方案1】:

使用 lubridate 包中的 %m+% 添加天、月或年非常简单:

library(lubridate)

x <- as.Date("2016-01-01")
x %m+% days(1)

给出:

[1] "2016-01-02"

要添加月份或年份,您可以使用monthsyears 而不是days

> x %m+% months(1)
[1] "2016-02-01"
> x %m+% years(1)
[1] "2017-01-01"

【讨论】:

  • 谢谢!效果很好,而且很容易
  • 如果您在 2 月 29 日添加不属于 4 个时间表的年份,则润滑失败。一种解决方案:使用POSIXlt
  • @giordano 或使用来自lubridate%m+%;查看答案的更新
  • @Jaap 太好了!谢谢。
猜你喜欢
  • 1970-01-01
  • 2011-07-07
  • 2015-03-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 2018-02-08
  • 1970-01-01
相关资源
最近更新 更多