我想将 yymmdd 格式的日期转换为 YYYYMMDD,但是当使用 simpledateformat 类时,我得到的是 1970 年之后的年份,但要求是 1970 年之前的年份。
问问题
188 次
1 回答
3
java.time
解析输入
控制 2 位数年份解释的方法yymmdd
是通过.appendValueReduced
DateTimeFormatterBuilder
DateTimeFormatter twoDigitFormatter = new DateTimeFormatterBuilder()
.appendValueReduced(ChronoField.YEAR, 2, 2, 1870)
.appendPattern("MMdd")
.toFormatter();
String exampleInput = "691129";
LocalDate date = LocalDate.parse(exampleInput, twoDigitFormatter);
提供 1870 年的基准年会导致在 1870 到 1969 范围内解释两位数的年份(因此总是在 1970 年之前)。根据您的要求提供不同的基准年。此外,除非您确定 100 年内的所有输入年份都是预期且有效的,否则我建议您对解析日期进行范围检查。
格式化和打印输出
DateTimeFormatter fourDigitFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
String result = date.format(fourDigitFormatter);
System.out.println(result);
此示例中的输出为:
19691129
如果输入为700114
,则输出为:
18700114
使用 LocalDate 保留您的日期
与其将日期从一种字符串格式转换为另一种格式,我建议最好将日期保存在 a 中LocalDate
,而不是字符串中(就像您不在字符串中保留整数值一样)。当您的程序接受字符串输入时,LocalDate
立即解析为 a 。只有当它需要给出字符串输出时,才将其格式化LocalDate
为字符串。出于这个原因,我还将解析与上面的格式分开。
关联
Oracle 教程:日期时间解释如何使用 java.time。
于 2019-07-11T17:05:25.627 回答