要求:以儒略格式获取日期,将其与当前日期进行比较,从中获取月份和年份。
以输出格式转换。
输入格式:yydddd输出格式:yymm
JDK 8
我可以使用的一种方法是使用日期:
Date myDateWrong = new SimpleDateFormat("yyyyddd").parse("2020366");
任何更清洁的方式?
我建议您使用现代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。