最好转换为Date
班级,因为当我们延长年份时,两位数的年份可能会成为问题。
library(chron)
date1 <- as.Date("01/31/80", format = "%m/%d/%y")
date2 <- as.Date("01/03/30", format = "%m/%d/%y")
在这里,转换是正确的
date1
#[1] "1980-01-31"
date2
#[1] "2030-01-03"
基于?seq.dates
,我们可以传递一个character
字符串或numeric
值(将 'Date' 类转换为 'numeric'
length(seq.dates(as.numeric(date1), as.numeric(date2), by = "months"))
#[1] 600
或julian
约会
j1 <- julian(date1, origin = as.Date('1970-01-01'))
j2 <- julian(date2, origin = as.Date('1970-01-01'))
length(seq.dates(j1, j2, by = 'months'))
#[1] 600
或使用 4 位数的年份character
格式
length(chron::seq.dates("01/31/1980", "01/03/2030", by="months"))
#[1] 600
如果日期已经有 2 位数字,可以插入特定数字sub
sub("(\\d+)$", "20\\1", "01/03/30")
#[1] "01/03/2030"
并将该值传递给seq.dates
length(seq.dates("01/31/80", sub("(\\d+)$", "20\\1", "01/03/30"), by = "months"))
#[1] 600