java - Is there a way to get pattern of a given date string Or from a LocalDate

房东的猫 提交于 2021-02-10 18:44:30

问题


I have a LocalDate object but i am struggling to find the pattern programatically using the DateTimeFormatter class in Java 8. Is there a way to do it or any 3rd party library for this?

I have tried the following but I do not want to use DateFormat class as this is not recommended.

LocalDateTime.parse("8/22/19 4:39 PM").format(DateTimeFormatter.ofPattern(pattern1).withLocale(Locale.getDefault()))

"Prints this which is what i kind of want -> M/d/yy h:mm a (I really want 'mm/dd/yyyy h:mm')

Although if i try that above pattern string to parse a date string it fails. Gives me this excepton"

Exception in thread "main" java.time.format.DateTimeParseException: Text '8/22/19 4:39 PM' could not be parsed at index 0
at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)

"The reason I want this behaviour is that there are locale specific date patterns configured in our i18n file. In case those are unavailable(Not configured) I need to supply with the jdk locale/zone specific date pattern. The DateFormat class kind of gives me but not exactly"


回答1:


Here is an example using DateTimeFormatter converting from and to String. Note that I use LocalDateTime rather than LocalDate since time is included as well.

DateTimeFormatter formatterWithTime = DateTimeFormatter.ofPattern("MM/dd/yy h:mm a").withLocale(Locale.US);

String outWithTime = formatterWithTime.format(LocalDateTime.now());
System.out.println(outWithTime);

String in = "08/22/19 4:39 PM";
LocalDateTime ldt = LocalDateTime.from(formatterWithTime.parse(in));
System.out.println(ldt);

This prints

08/23/19 10:44 AM
2019-08-22T16:39



来源:https://stackoverflow.com/questions/57622410/java-is-there-a-way-to-get-pattern-of-a-given-date-string-or-from-a-localdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!