在日期时间字符串中解析日期的序数指示符(st,nd,rd,th) [英] Parsing a date’s ordinal indicator ( st, nd, rd, th ) in a date-time string

查看:178
本文介绍了在日期时间字符串中解析日期的序数指示符(st,nd,rd,th)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了 SimpleDateFormat javadoc ,但我无法找到解析序数指标的日期格式如下:

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 不必截断字符串?

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屋!

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