如果你的 5 位数字真的只需要补零,那么
dato_s <- sprintf("%06d", dato)
dato_s
# [1] "311230" "311245" "311267" "311268" "310169" "201104" "051230" "051269" "051204"
从那里,您关于"dates before 1969"?strptime
的问题,看看'%y'
模式:
'%y' Year without century (00-99). On input, values 00 to 68 are
prefixed by 20 and 69 to 99 by 19 - that is the behaviour
specified by the 2018 POSIX standard, but it does also say
'it is expected that in a future version the default century
inferred from a 2-digit year will change'.
因此,如果您有特定的备用年份,则需要在发送到之前添加世纪as.Date
(使用strptime
-patterns)。
dato_d <- as.Date(gsub("([0-4][0-9])$", "20\\1",
gsub("([5-9][0-9])$", "19\\1", dato_s)),
format = "%d%m%Y")
dato_d
# [1] "2030-12-31" "2045-12-31" "1967-12-31" "1968-12-31" "1969-01-31" "2004-11-20"
# [7] "2030-12-05" "1969-12-05" "2004-12-05"
在这种情况下,我假设 50-99 将是 1900,其他都是 2000。如果您需要 40 或 30,请随意调整模式:将数字添加到第二个模式(例如,[3-9]
)并从第一个模式中删除(例如,[0-2]
),确保所有十年都包含在一个模式中,而不是“两者都”而不是“两者”。
借用艾伦的回答,我喜欢这个假设now()
(因为你确实提到了“出生于”)。没有lubridate
,试试这个:
dato_s <- sprintf("%06d", dato)
dato_d <- as.Date(dato_s, format = "%d%m%y")
dato_d[ dato_d > Sys.Date() ] <-
as.Date(sub("([0-9]{2})$", "19\\1", dato_s[ dato_d > Sys.Date() ]), format = "%d%m%Y")
dato_d
# [1] "1930-12-31" "1945-12-31" "1967-12-31" "1968-12-31" "1969-01-31" "2004-11-20"
# [7] "1930-12-05" "1969-12-05" "2004-12-05"