将字符串转换为日期-罗马月份 [英] Convert string to date - roman month

查看:55
本文介绍了将字符串转换为日期-罗马月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下字符串:"05 X 02"。我怎样才能把它转换成日期呢?我不想将其转换为字符串"05 10 02",然后转换为日期。有可能吗?

感谢您的帮助。

到目前为止,我正在尝试使用

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd M/L yy");

但它不起作用。我也尝试使用DateTimeFormatterBuilder,但在这里我完全迷路了。

推荐答案

您可以将默认格式符号更改为具有月份的浪漫数字

DateFormatSymbols symbols = DateFormatSymbols.getInstance();

final String[] romanMonths =  {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII"};
symbols.setMonths(romanMonths);

SimpleDateFormat formatter = new SimpleDateFormat("dd MMMM yy", symbols);

System.out.println("My date " + formatter.parse("05 X 02"));

Here是关于如何拥有自定义格式符号的很好的教程。

您可以选择通过setShortMonths()更改短月份或通过setMonths()更改完整月

更新:以下是来自JDK8的DateTimeFormatterBuilder版本

static final ImmutableMap<Long, String> ROMAN_MONTHS = ImmutableMap.<Long, String>builder()
                .put(1L, "I").put(2L, "II").put(3L, "III").put(4L, "IV").put(5L, "V")
                .put(6L, "VI").put(7L, "VII").put(8L, "VIII").put(9L, "IX").put(10L, "X")
                .put(11L, "XI").put(12L, "XII").build();

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NORMAL)
                    .appendLiteral(' ')
                    .appendText(ChronoField.MONTH_OF_YEAR, ROMAN_MONTHS)
                    .appendLiteral(' ')
                    .appendValue(ChronoField.YEAR, 4)
                    .toFormatter();

System.out.println("My date " + formatter.parse("5 X 2012"));

这篇关于将字符串转换为日期-罗马月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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