Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

java - DateTimeFormatter Support for Single Digit Day of Month and Month of Year

DateTimeFormmater doesn't seem to handle single digit day of the month:

String format = "MM/dd/yyyy";
String date   = "5/3/1969";
System.out.println(new SimpleDateFormat(format).parse(date));
System.out.println(LocalDate.parse(date, DateTimeFormatter.ofPattern(format)));

In this example, SimpleDateFormat correctly parses the date, but DateTimeFormatter throws an exception. If I were to use zero padded dates, e.g., "05/03/1969", both work. However, if either the day of month or the month of year are single digit, then DateTimeFormatter throws an exception.

What is the right DateTimeFormatter format to parse both one and two digit day of month and month of year?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the documentation:

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding.

So the format specifier you want is M/d/yyyy, using single letter forms. Of course, it will still parse date Strings like "12/30/1969" correctly as for these day/month values, two digits are the “minimum number of digits”.

The important difference is that MM and dd require zero padding, not that M and d can’t handle values greater than 9 (that would be a bit… unusual).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...