java-是否有办法从给定的日期字符串或从LocalDate获取模式 [英] java - Is there a way to get pattern of a given date string Or from a LocalDate

查看:71
本文介绍了java-是否有办法从给定的日期字符串或从LocalDate获取模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个LocalDate对象,但是我正在努力使用Java 8中的DateTimeFormatter类以编程方式找到模式.是否有办法做到这一点或任何第三方库?

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?

我尝试了以下操作,但由于不建议使用DateFormat类,因此不建议使用.

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()))

打印出我想要的样式-> M/d/yy h:mm a(我真的想要'mm/dd/yyyy h:mm')

"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)

我想要此行为的原因是,我们的i18n文件中配置了特定于语言环境的日期模式.如果这些模式不可用(未配置),我需要提供jdk特定于语言环境/区域的日期模式.DateFormat类有点给我,但不完全是我."

"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"

推荐答案

以下是使用DateTimeFormatter从String转换为String的示例.请注意,由于还包括时间,因此我使用LocalDateTime而不是LocalDate.

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);

此打印

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

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

这篇关于java-是否有办法从给定的日期字符串或从LocalDate获取模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆