Java – resolves the order indicator of the date in the date time string (st, Nd, RD, th)

I checked the simpledateformat Javadoc, but I couldn't find a way to parse the ordinal indicator in such a date format:

Feb 13th 2015 9:00AM

I tried "MMM DD yyyy HH: MMA", but must these days be correct in quantity?

You can use simpledateformat to parse the "13th" date without truncating the string?

Solution

Java's simpledateformat does not support ordinal suffixes, but ordinal suffixes are just eye candy - they are redundant and can be easily deleted for direct resolution:

Date date = new SimpleDateFormat("MMM dd yyyy hh:mma")
    .parse(str.replaceAll("(?<=\\d)(st|nd|rd|th)",""));

Replacing regular expressions is simple because these sequences will not appear elsewhere on the effective date

Process any language with any length of sequence number indicator as suffix:

Date date = new SimpleDateFormat("MMM dd yyyy hh:mma")
    .parse(str.replaceAll("(?<=\\d)(?=\\D* \\d+ )\\p{L}+",""));

Some languages, such as Mandarin, fill in their order indicators in advance, but can also be handled in an alternating way – stay as an exercise for readers:)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>