我面临的问题是,我需要将时间从24格式转换为AM/PM格式(反之亦然),通过time4j库删除多余的值,如纳秒和秒。
我使用time4j库是因为time4j不能处理time4j时区,我必须通过time4j来转换它们
从24小时格式到AM/PM的转换将取决于用户的本地化。我想把它(本土化)作为一个论据。本地化将看起来像"en-US“字符串。
例如,:如果用户本地化为"en-US“,则将24小时格式转换为AM/PM。否则保持现值。
或者,如果我已经定义了用户的本地化,那么最好以我需要的格式获得时间?
有什么办法吗?,请帮忙)
我不得不花很多时间读time4j文档,但是我的头脑被炸了
来全面了解我正在做的事情以及我的目的--所有这些:
我必须从我的数据库中获取用户timeZone,该数据库对应于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“是来自DB的timeZone。它对应于Microsoft时区名称
我的下一步是从用户时区获得时间/或时间戳,我已经将其转换为IANA时区。
我确实喜欢这样:
PlainTime currentTime = SystemClock.inZonalView(winZone).now().toTime();
//currentTime: "T17:31:37,057"其中"winZone“转换为timeZone (例如。“窗户~欧洲/基辅”)
,所以现在回到我的问题,我在文章的顶部描述了.
发布于 2018-06-16 09:09:18
只要您知道ChronoFormatter中的专用格式化程序API是基于的,这是直接的。
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 PlainTime 的格式-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版本肯定会改变大写。总的来说,为了获得更多的特性、更好的ChronoFormatter和更高的性能,我仍然建议使用i18n。例如,如果您使用不同的语言环境,使用Time4J解析am/pm文本的相反方法比在java.time中更可靠。
如果您喜欢在大写字母(或任何其他自定义格式)中与ChronoFormatter一起使用"AM“和"PM”,则还可以使用:
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 PMhttps://stackoverflow.com/questions/50875465
复制相似问题