My consumer received time format is String
with value 20/5/14_9:22:25
or 20/5/14_9:22:5
or 20/5/14_12:22:25
or 20/10/14_9:2:25
etc...
all the above have very diffrent date time pattern from yy/MM/dd_HH:mm:ss
and there can be many posiblity's of having single digit day,month,hour,minute and/or seconds.
is there a masterpattern which will i can use for DateTimeFormatter.ofPattern(format)
which will work for all the above pattern??
The patterns look the same
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/M/dd_H:mm:s");
LocalDate parsedDate = LocalDate.parse("20/5/14_9:22:25", formatter);
System.out.println(parsedDate);
parsedDate = LocalDate.parse("20/5/14_9:22:5", formatter);
System.out.println(parsedDate);
parsedDate = LocalDate.parse("20/10/14_9:22:25", formatter);
System.out.println(parsedDate);
output
2020-05-14
2020-05-14
2020-10-14
Counter-intuitively but very practically, for numbers one pattern letter, for example M
or H
, does not mean one digit but rather “as many digits as it takes”. So M
parses both 5
and 10
(and even 05
). H
parses 9
and 12
, etc. By contrast two pattern letters, for example MM
or HH
, means exactly two digits, so will not work for parsing neither a month of 5 nor an hour of 9. It would require 05
or 09
. Or as the documentation puts it:
Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary. …
So if you need to accept one-digit day of month or one-digit minute of the hour, also use one pattern letter d
and m
, respectively.
But having a hour of 29
(as you had in earlier versions of the question) is wrong.
Documentation link: DateTimeFormatter