问题
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??
回答1:
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
回答2:
The answer by Scary Wombat is to the point. I'm adding this answer to just let you know that apart from LocalDate
, the package, java.time
also has a LocalDateTime
which you can use to deal with date and time both as shown below:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yy/M/dd_H:mm:s");
LocalDateTime ldt = LocalDateTime.parse("20/5/14_9:22:25", formatter);
System.out.println(ldt);
ldt = LocalDateTime.parse("20/5/14_9:22:5", formatter);
System.out.println(ldt);
ldt = LocalDateTime.parse("20/10/14_9:22:25", formatter);
System.out.println(ldt);
}
}
Output:
2020-05-14T09:22:25
2020-05-14T09:22:05
2020-10-14T09:22:25
来源:https://stackoverflow.com/questions/61791762/is-there-master-date-time-pattern-which-will-work-for-every-similar-date-time-pa