首页 > 解决方案 > 在 Julia 中,如何将 DateFormat 年份设置为 19 表示 2019?

问题描述

我的日期看起来像“17-JAN-19”、“18-FEB-20”。当我尝试使用该Dates软件包时Date("17-JAN-19", "d-u-yy"),我得到了合理的结果0019-01-17。我可以这样做Date("17-JAN-19", "d-u-yy") + Year(2000),但这会引入新错误的可能性(我打算举闰年的例子,但尽管存在非常罕见的错误,但它通常有效Date("29-FEB-00", "d-u-yy")+Year(1900))。

是否有嵌入关于世纪的已知信息的日期格式?

标签: datejulia

解决方案


https://github.com/JuliaLang/julia/issues/30002中所述,将世纪分配给日期有多种启发式方法。我建议明确并通过辅助函数处理它。

const NOCENTURYDF = DateFormat("d-u-y")
"""
    parse_date(obj::AbstractString,
               breakpoint::Integer = year(now()) - 2000,
               century::Integer = 20)

Parses date in according to DateFormat("d-u-y") after attaching century information.
If the year portion is greater that the current year,
it assumes it corresponds to the previous century.
"""
function parse_date(obj::AbstractString,
                    breakpoint::Integer = year(now()) - 2000,
                    century::Integer = 20)
    # breakpoint = year(now()) - 2000
    # century = year(now()) ÷ 100
    @assert 0 ≤ breakpoint ≤ 99
    yy = rpad(parse(Int, match(r"\d{2}$", obj).match), 2, '0')
    Date(string(obj[1:7],
                century - (parse(Int, yy) > breakpoint),
                yy),
         NOCENTURYDF)
end
parse_date("17-JAN-19")
parse_date("29-FEB-00")

推荐阅读