如何在Java中转换朱利安日期

问题描述 投票:0回答:1

要求:以儒略格式获取日期,将其与当前日期进行比较,从中获取月份和年份。

以输出格式转换。

输入格式:yydddd输出格式:yymm

JDK 8

我可以使用的一种方法是使用日期:

Date myDateWrong = new SimpleDateFormat("yyyyddd").parse("2020366");

任何更清洁的方式?

java date julian-date java-date
1个回答
0
投票

java.time

我建议您使用现代Java日期和时间API java.time进行日期工作。

    DateTimeFormatter dayOfYearFormatter
            = DateTimeFormatter.ofPattern("uuuuDDD");
    DateTimeFormatter yearMonthFormatter
            = DateTimeFormatter.ofPattern("uuMM");

    String yyyydddString = "2020366";
    LocalDate date = LocalDate.parse(yyyydddString, dayOfYearFormatter);
    String output = date.format(yearMonthFormatter);

    System.out.println(output);

输出为:

2012

所以2020年12月。

您的代码出了什么问题?

无论您使用现代DateTimeFormatter还是旧的麻烦的SimpleDateFormat,小写d表示日期of of month,大写D表示日期of of year。无论如何,为什么它与SimpleDateFormat一起使用是因为该类在没有给出月份的情况下默认将月份默认为一月。因此,您的日期被解析为一月的第366天。什么?!没错,SimpleDateFormat的另一个令人困惑的特征是,使用默认设置,它很乐意解析不存在的日期。当一月只有31天时,它只是推算到接下来的几个月,直到12月31日,即您打算的那一天。 SimpleDateFormat充满了这些令人讨厌的惊喜。我建议您永远不要再使用该类。

链接

Oracle tutorial: Date Time解释如何使用java.time。

© www.soinside.com 2019 - 2024. All rights reserved.