我想将 yymmdd 格式的日期转换为 YYYYMMDD,但是在使用 simpledateformat 类时,我得到的是 1970 年之后的年份,但要求是 1970 年之前的年份。
Parsing input
The way to control the interpretation of the 2-digit year in yymmdd
is through the appendValueReduced
method of DateTimeFormatterBuilder
.
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). 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.
Formatting and printing output
DateTimeFormatter fourDigitFormatter = DateTimeFormatter.ofPattern("uuuuMMdd");
String result = date.format(fourDigitFormatter);
System.out.println(result);
Output in this example is:
19691129
If instead input was 700114
, output is:
18700114
Use LocalDate for keeping your date
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). When your program accepts string input, parse into a LocalDate
at once. Only when it needs to give string output, format the LocalDate
back into a string. For this reason I have also separated parsing from formatting above.
Link
Oracle tutorial: Date Time explaining how to use java.time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.