简体   繁体   English

有没有办法在 1970 年之前转换 java 中的日期?

[英]is there any way to convert the date in java prior to 1970?

我想将 yymmdd 格式的日期转换为 YYYYMMDD,但是在使用 simpledateformat 类时,我得到的是 1970 年之后的年份,但要求是 1970 年之前的年份。

java.time时间

Parsing input解析输入

The way to control the interpretation of the 2-digit year in yymmdd is through the appendValueReduced method of DateTimeFormatterBuilder .控制yymmdd 2 位年份的解释的方法是通过DateTimeFormatterBuilderappendValueReduced方法。

    DateTimeFormatter twoDigitFormatter = new DateTimeFormatterBuilder()
            .appendValueReduced(ChronoField.YEAR, 2, 2, 1870)
            .appendPattern("MMdd")
            .toFormatter();
    String exampleInput = "691129";
    LocalDate date = LocalDate.parse(exampleInput, twoDigitFormatter);

Supplying a base year of 1870 causes two-digit years to be interpreted in the range 1870 through 1969 (so always prior to 1970).提供 1870 年的基准年会导致在 1870 年到 1969 年的范围内解释两位数的年份(因此总是在 1970 年之前)。 Supply a different base year according to your requirements.根据您的要求提供不同的基准年。 Also unless you are sure that input years all across a period of 100 years are expected and valid, I recommend you do a range check of the parsed date.此外,除非您确定整个 100 年的输入年份都是预期且有效的,否则我建议您对解析日期进行范围检查。

Formatting and printing output格式化和打印输出

    DateTimeFormatter fourDigitFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
    String result = date.format(fourDigitFormatter);
    System.out.println(result);

Output in this example is:此示例中的输出为:

19691129 19691129

If instead input was 700114 , output is:如果输入为700114 ,则输出为:

18700114 18700114

Use LocalDate for keeping your date使用 LocalDate 来保存您的日期

Instead of converting your date from one string format to another, I suggest that it's better to keep your date in a LocalDate , not a string (just like you don't keep an integer value in a string).与其将日期从一种字符串格式转换为另一种格式,我建议最好将日期保存在LocalDate ,而不是字符串中(就像您不在字符串中保存整数值一样)。 When your program accepts string input, parse into a LocalDate at once.当您的程序接受字符串输入时,立即解析为LocalDate Only when it needs to give string output, format the LocalDate back into a string.只有当它需要给出字符串输出时,才将LocalDate格式化回字符串。 For this reason I have also separated parsing from formatting above.出于这个原因,我还将解析与上面的格式分开。

Link关联

Oracle tutorial: Date Time explaining how to use java.time. Oracle 教程:解释如何使用 java.time 的日期时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM