将posix时间加一年 [英] Add one year to a posix time
问题描述
我有一个类似"2016-01-01"
(YYYY-MM-DD)的日期,并且我正在使用 as.numeric(as.POSIXct(...))
用作整数.
I have a date like "2016-01-01"
(YYYY-MM-DD) and I'm using as.numeric(as.POSIXct(...))
to use it as an Integer.
我的问题是,有没有办法将这个日期添加一年,一个月或一天?我的意思是,如果我在2016年增加一年,就不会与2015年(双性恋的东西)增加一年相同.
My question is, is there a way to add to this date a year, a month or a day ? I mean, if I add one year to 2016 it wont be the same as adding a year to 2015 (bissextile stuff).
与1月1日增加32天相同,与2月1日增加32天相同(因为可能会更改的天数)
Same as adding 32 days to January 01 wont be the same as adding 32 days to February 01 (because of number of days that may change)
我设法使它工作了好几年甚至几个月,但我也想实施天
I managed to have something that works for years and months but I'd like to implement days as well
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
添加月/年,然后重建一个干净的字符串并将其转换为整数
Basically what I'm doing is from a DATE_START
integer transform it into gregorian then add the months / years from lst
then rebuild a clean string and reconvert it to integer.
转换int< ---> gregorian是使用POSIXct
N.B. Conversion int <---> gregorian are done with POSIXct
我不确定我的解释是否很好,但是还是要谢谢你:)
I'm not sure if I explained it well, but thank you anyway :)
推荐答案
使用lubridate软件包中的%m +%
添加日期,月份或年份非常简单:
Adding a day, month or year is quite straightforward with %m+%
from the lubridate package:
library(lubridate)
x <- as.Date("2016-01-01")
x %m+% days(1)
给出:
[1] "2016-01-02"
要添加月份或年份,可以使用 months
或 years
代替 days
:
For adding months or years, you can use months
or years
instead of days
:
> x %m+% months(1)
[1] "2016-02-01"
> x %m+% years(1)
[1] "2017-01-01"
这篇关于将posix时间加一年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!