在posix时间添加一年

Bob*_*Gob 7 r date posixct

我有一个像"2016-01-01"(YYYY-MM-DD)的日期,我正在as.numeric(as.POSIXct(...))使用它作为整数.

我的问题是,有没有办法在一年,一个月或一天中添加到这个日期?我的意思是,如果我在2016年增加一年,它将与2015年增加一年(bissextile stuff)相同.

与在1月1日添加32天相同,与在2月01日添加32天相同(因为可能更改的天数)

我设法把东西了年和月的作品,但我想实现以及

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
)
Run Code Online (Sandbox Code Playgroud)

基本上我正在做的是从DATE_START整数转换为格里高利,然后添加月/年,lst然后重建一个干净的字符串并将其重新转换为整数.

NB转换int <---> gregorian是用POSIXct完成的

我不确定我是否解释得很好,但无论如何谢谢你:)

Jaa*_*aap 17

%m+%从lubridate包中添加日,月或年是非常简单的:

library(lubridate)

x <- as.Date("2016-01-01")
x %m+% days(1)
Run Code Online (Sandbox Code Playgroud)

这使:

[1] "2016-01-02"
Run Code Online (Sandbox Code Playgroud)

对于添加月份或年份,您可以使用monthsyears代替days:

> x %m+% months(1)
[1] "2016-02-01"
> x %m+% years(1)
[1] "2017-01-01"
Run Code Online (Sandbox Code Playgroud)