解析日期时间字符串中日期的序数指示符( st, nd, rd, th ) [英] Parsing a date’s ordinal indicator ( st, nd, rd, th ) in a date-time string
问题描述
我检查了 SimpleDateFormat
javadoc,但我找不到解析序数指标的方法a> 以这样的日期格式:
I checked the SimpleDateFormat
javadoc, but I am not able to find a way to parse the ordinal indicator in a date format like this:
Feb 13th 2015 9:00AM
我尝试了 "MMM dd yyyy hh:mma"
,但是天数必须很多才能正确?
I tried "MMM dd yyyy hh:mma"
, but the days have to be in number for it to be correct?
是否可以使用 SimpleDateFormat
解析第 13 个"日期而不必截断字符串?
Is it possible to parse the "13th" date using a SimpleDateFormat
without having to truncate the string?
推荐答案
Java 的 SimpleDateFormat 不支持序数后缀,但序数后缀只是令人赏心悦目的 - 它是多余的并且可以轻松删除以允许直接解析:
Java's SimpleDateFormat doesn't support an ordinal suffix, but the ordinal suffix is just eye candy - it is redundant and can easily be removed to allow a straightforward parse:
Date date = new SimpleDateFormat("MMM dd yyyy hh:mma")
.parse(str.replaceAll("(?<=\d)(st|nd|rd|th)", ""));
替换正则表达式非常简单,因为这些序列不会出现在有效日期的其他任何地方.
The replace regex is so simple because those sequences won't appear anywhere else in a valid date.
处理将任何语言的任何长度的序数指示字符作为后缀的任何语言:
To handle any language that appends any length of ordinal indicator characters from any language as a suffix:
Date date = new SimpleDateFormat("MMM dd yyyy hh:mma")
.parse(str.replaceAll("(?<=\d)(?=\D* \d+ )\p{L}+", ""));
某些语言,例如普通话,在它们的序数指示符之前,但这也可以使用交替来处理 - 留给读者练习:)
Some languages, eg Mandarin, prepend their ordinal indicator, but that could be handled too using an alternation - left as an exercise for the reader :)
这篇关于解析日期时间字符串中日期的序数指示符( st, nd, rd, th )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!