如何在Java DateTime API中解析带有日语数字的日期字符串 [英] How to Parse Date Strings with 🎌 Japanese Numbers in Java DateTime API

查看:53
本文介绍了如何在Java DateTime API中解析带有日语数字的日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问了[How to parse 🎌 Japanese Era Date string values into LocalDate & LocalDateTime]后,
我对下面这个案例很好奇;

明治二十三年十一月二十九日

有没有办法将日文日历字符(本质上是日文日期)上的Japanese numbers解析为LocalDate?仅使用Java DateTime API。我不想修改输入字符串值,只想让API来处理识别。

推荐答案

对于阅读的任何人来说,您的示例日期字符串包含一个纪元指示符、纪年23(在本例中对应于公元1890年公元格里高利)、月11和月29日。月和日与公历中的相同。

由于日语数字并非完全按位置排列(例如,与阿拉伯数字一样),DateTimeFormatter不会单独解析它们。因此,我们通过提供这些数字在日语(和中文)中的显示来帮助它。DateTimeFormatterBuilder有一个重载的appendText方法,该方法接受包含所有可能数字的映射作为文本。我的代码示例并不完整,但应该可以帮助您入门。

    Locale japaneseJapan = Locale.forLanguageTag("ja-JP");

    Map<Long, String> numbers = Map.ofEntries(
            Map.entry(1L, "u4e00"),
            Map.entry(2L, "u4e8c"),
            Map.entry(3L, "u4e09"),
            Map.entry(4L, "u56db"),
            Map.entry(5L, "u4e94"),
            Map.entry(6L, "u516d"),
            Map.entry(7L, "u4e03"),
            Map.entry(8L, "u516b"),
            Map.entry(9L, "u4e5d"),
            Map.entry(10L, "u5341"),
            Map.entry(11L, "u5341u4e00"),
            Map.entry(12L, "u5341u4e8c"),
            Map.entry(13L, "u5341u4e09"),
            Map.entry(14L, "u5341u56db"),
            Map.entry(15L, "u5341u4e94"),
            Map.entry(16L, "u5341u516d"),
            Map.entry(17L, "u5341u4e03"),
            Map.entry(18L, "u5341u516b"),
            Map.entry(19L, "u5341u4e5d"),
            Map.entry(20L, "u4e8cu5341"),
            Map.entry(21L, "u4e8cu5341u4e00"),
            Map.entry(22L, "u4e8cu5341u4e8c"),
            Map.entry(23L, "u4e8cu5341u4e09"),
            Map.entry(24L, "u4e8cu5341u56db"),
            Map.entry(25L, "u4e8cu5341u4e94"),
            Map.entry(26L, "u4e8cu5341u516d"),
            Map.entry(27L, "u4e8cu5341u4e03"),
            Map.entry(28L, "u4e8cu5341u516b"),
            Map.entry(29L, "u4e8cu5341u4e5d"),
            Map.entry(30L, "u4e09u4e8cu5341"));

    DateTimeFormatter japaneseformatter = new DateTimeFormatterBuilder()
            .appendPattern("GGGG")
            .appendText(ChronoField.YEAR_OF_ERA, numbers)
            .appendLiteral('u5e74')
            .appendText(ChronoField.MONTH_OF_YEAR, numbers)
            .appendLiteral('u6708')
            .appendText(ChronoField.DAY_OF_MONTH, numbers)
            .appendLiteral('u65e5')
            .toFormatter(japaneseJapan)
            .withChronology(JapaneseChronology.INSTANCE);

    String dateString = "明治二十三年十一月二十九日";
    System.out.println(dateString + " is parsed into " + LocalDate.parse(dateString, japaneseformatter));

此示例的输出为:

明治二十三年十一月二十九日解析为1890-11-29

假设一个时代可以超过30年,你需要向地图提供更多的数字。您可以做得比我好得多(还可以检查我的数据中的错误)。使用几个嵌套循环来填充地图可能是最好的(不容易出错),但我不确定我是否能正确完成,所以我将这一部分留给您。

今天我学习了一些关于日语数字的知识。

我使用的一些链接

这篇关于如何在Java DateTime API中解析带有日语数字的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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