如何将时间 24 小时转换为 AM/PM 并通过 time4j 删除纳秒和秒?



我面临着我需要将时间从 24 格式转换为 AM/PM 格式(反之亦然(的问题,通过 time4j 库删除纳秒和秒等冗余值。

我正在使用time4j库,因为Java无法处理Windows时区,我必须通过time4j转换它们

从 24 小时格式转换为 AM/PM 格式将取决于用户的本地化。我想将其(本地化(作为参数传递。本地化将类似于"en-US"字符串。

例如:如果用户本地化为"en-US",则将 24 小时格式转换为 AM/PM。 否则保持当前值。

或者,当我已经定义了用户的本地化时,也许最好以我需要的格式获得时间?

任何想法如何做到这一点?请帮忙(

我必须花很多时间阅读时间4j文档,但我的头脑被炸毁了

要全面了解我正在做的事情以及所有这些目的:

我必须从对应于Windows时区的数据库中获取用户时区,并将其转换为IANA时区。我已经通过这种方法做到了这一点

WindowsZone wzn = WindowsZone.of(userTimeZoneId); //userTimeZoneId="eg. FLE Standart Time"
TZID winZone = wzn.resolveSmart(new Locale("","001"));
System.out.println(winZone.canonical()); // WINDOWS~Europe/Kiev

其中"userTimeZoneId"是数据库中的时区。它对应于时区的名称Microsoft

我的下一步是从用户时区获取时间/或时间戳,我已经将其转换为 IANA 时区。

我确实喜欢这个:

PlainTime currentTime = SystemClock.inZonalView(winZone).now().toTime(); 
//currentTime: "T17:31:37,057"

其中"winZone"转换了时区(例如。"视窗~欧洲/基辅"(

所以现在回到我在帖子顶部描述的问题。

  1. 也许当我已经定义了用户的本地化时,最好以我需要的格式获得时间?

  2. 如何将时间从 24 格式转换为 AM/PM,反之亦然?

  3. 如何删除纳秒和秒等冗余值?

  4. 如何在转化中使用用户本地化?

只要您知道 Time4J 中的专用格式化程序 API 基于 ChronoFormatter,这很简单:

Locale ukraine = new Locale("en", "UA"); // or use new Locale("en", "001") for worldwide
TZID winZone = WindowsZone.of("FLE Standard Time").resolveSmart(ukraine);
PlainTime currentTime = SystemClock.inZonalView(winZone).now().toTime();
System.out.println(currentTime); // T12:02:40,344
// truncate seconds and nanoseconds
currentTime = currentTime.with(PlainTime.PRECISION, ClockUnit.MINUTES);
System.out.println(currentTime); // T12:02
// format in am/pm-notation
ChronoFormatter<PlainTime> f1 =
ChronoFormatter.ofTimePattern("h:mm a", PatternType.CLDR, Locale.US);
String formatted1 = f1.format(currentTime);
System.out.println(formatted1); // 12:02 pm
// or use styled formatter (which has only limited control over displayed precision)
ChronoFormatter<PlainTime> f2 = 
ChronoFormatter.ofTimeStyle(DisplayMode.SHORT, Locale.US);
String formatted2 = f2.format(currentTime);
System.out.println(formatted2); // 12:02 pm

如果要让区域设置控制格式模式,则基于样式的解决方案(如上文 Time4J 所示(是合适的。例如,德语区域设置将打印"12:02"而不是"12:02 pm"(美国(。

顺便说一下,如果你愿意,你也可以自由使用java.time的格式API,因为PlainTime实现了JSR-310接口TemporalAccessor

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mm a", Locale.US);
System.out.println(dtf.format(currentTime)); // 12:02 PM

这里的大写不同源于这样一个事实,即JDK(至少在我的系统上(仍然使用较旧的CLDR数据进行国际化,而Time4J拥有基于实际CLDR版本v33的自己的资源。未来的Java版本肯定会改变大小写。总的来说,为了更多的功能、更好的 i18n 和更高的性能,我仍然建议使用ChronoFormatter。例如,使用 Time4J 解析 am/pm-literal 的反向方式比使用不同的语言环境时在java.time中更可靠。

如果您想将大写字母(或任何其他自定义格式(中的"AM"和"PM"与ChronoFormatter一起使用,那么您还可以使用:

Map<Meridiem, String> map = new EnumMap<>(Meridiem.class);
map.put(Meridiem.AM, "AM");
map.put(Meridiem.PM, "PM");
ChronoFormatter<PlainTime> f3 =
ChronoFormatter
.setUp(PlainTime.axis(), Locale.ROOT)
.addPattern("h:mm ", PatternType.CLDR)
.addText(PlainTime.AM_PM_OF_DAY, map)
.build();
String formatted3 = f3.format(currentTime);
System.out.println(formatted3); // 12:02 PM

最新更新