用户将以不同模式向我的应用程序输入日期。对于两位数年份,他还必须确定基准日期。
示例:
模式=yy-MM-dd
枢轴日期 = 70 (我以编程方式添加当前千年和上个世纪以获得更多动态 => 1970)
69-04-22 变为 2069-04-22
70-04-22 变为 1970-04-22
如 this answer 中所述当日期模式(此处为 ddMMyy )已知时,构建 DateTimeFormatter
很容易。
但由于用户输入了模式,我不确定如何正确构建 DateTimeFormatterBuilder
。我无法对其进行硬编码。
我是否必须自己解析模式并按正确的顺序调用 appendPattern()
和 appendValueReduced()
?或者有内置的解决方案吗?
最佳答案
这里是 Java-8 解决方案(它看起来更像是一个 hack):
String pattern = "MM/dd/yy 'US'"; // user-input
String text = "10/04/69 US"; // user-input
Locale locale = Locale.US; // user-input, too?
int yy = pattern.indexOf("yy");
DateTimeFormatter dtf;
if (
(yy != -1) // explanation: condition ensures exactly two letters y
&& ((yy + 2 >= pattern.length()) || pattern.charAt(yy + 2) != 'y')
) {
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
String part1 = pattern.substring(0, yy);
if (!part1.isEmpty()) {
builder.appendPattern(part1);
}
builder.appendValueReduced(ChronoField.YEAR, 2, 2, 1970);
String part2 = pattern.substring(yy + 2);
if (!part2.isEmpty()) {
builder.appendPattern(part2);
}
dtf = builder.toFormatter(locale);
} else {
dtf = DateTimeFormatter.ofPattern(pattern, locale);
}
LocalDate ld = LocalDate.parse(text, dtf);
System.out.println("user-date: " + ld); // 2069-10-04
只有一个小小的警告:如果任何用户产生疯狂的想法,在模式中单独定义两个“yy”,那么所提出的解决方案将失败。正确的解决方案需要对模式字符进行某种迭代,但我认为这太过分了,所以我将其留在这里。
为了进行比较,使用我的外部库 Time4J 可以实现以下简短的解决方案,因为它的解析引擎还具有设置任何合适的格式属性的概念:
LocalDate ld =
ChronoFormatter.ofDatePattern(pattern, PatternType.CLDR, locale)
.with(Attributes.PIVOT_YEAR, 2070).parse(text).toTemporalAccessor();
关于java - 解析2位数年份: Setting the pivot date with an unknown date pattern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32782645/