如何用可选部分解析日期时间? [英] How to parse datetime with optional sections?
本文介绍了如何用可选部分解析日期时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的日期时间可能是以下格式之一:
I've datetime that may be one of the following formats:
- MM / dd / yy
- M / dd / yy
- MM / d / yy
- M / d / yy
- 以上任何一项HH:mm
- 以上任何一位有4位数的年份
- MM/dd/yy
- M/dd/yy
- MM/d/yy
- M/d/yy
- Any of the above with HH:mm
- Any of the above with 4-digit year
我构建的 DateTimeFormatter
如下:
new DateTimeFormatterBuilder()
.appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NEVER)
.appendLiteral('/')
.appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER)
.appendLiteral('/')
.appendValue(ChronoField.YEAR_OF_ERA, 2, 4, SignStyle.NEVER)
.optionalStart()
.appendLiteral(' ')
.appendValue(HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(MINUTE_OF_HOUR, 2)
.toFormatter();
但无法格式化 2/9/17
。为什么?
But it fails to format 2/9/17
. Why?
推荐答案
这样有效:
new DateTimeFormatterBuilder()
.appendValue(ChronoField.MONTH_OF_YEAR, 1, 2, SignStyle.NEVER)
.appendLiteral('/')
.appendValue(ChronoField.DAY_OF_MONTH, 1, 2, SignStyle.NEVER)
.appendLiteral('/')
.appendValueReduced(ChronoField.YEAR, 2, 4, yearMonth.getYear())
.appendPattern("[ HH:mm]")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.toFormatter();
我在回复Meno Hochschild评论时发布的错误是通过设置可选小时和分钟的默认值来修复的。
The error I posted in response to Meno Hochschild's comment is fixed by setting defaults for the optional hours and minutes.
这篇关于如何用可选部分解析日期时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文