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
I tried "MMM dd yyyy hh:mma"
, but the days have to be in number for it to be correct?
Is it possible to parse the "13th" date using a SimpleDateFormat
without having to truncate the string?
You should be using RuleBasedNumberFormat. It works perfectly and it's respectful of the Locale.
In case someone finds it useful: DateTimeFormatter builder. This formatter allows you to format and to parse UK dates with ordinal suffixes (eg. "1st January 2017"):
Plus a fragment of the test class:
PS. I used Greg Mattes' solution for ordinal suffixes from here: How do you format the day of the month to say "11th", "21st" or "23rd" in Java? (ordinal indicator)
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:
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:
Some languages, eg Mandarin, prepend their ordinal indicator, but that could be handled too using an alternation - left as an exercise for the reader :)
Java 8 answer (and Java 6 and 7) (because when this question was asked in 2015, the replacement for
SimpleDateFormat
was already out):With the sample date from the question this yiedls:
In the format pattern
[]
denotes optional parts and''
denotes literal parts. So the pattern says that the number may be followed byst
,nd
,rd
orth
.To use this in Java 6 or 7 you need ThreeTen Backport. Or for Android ThreeTenABP.
Since those suffixes are special for English, and other languages/locales have completely other usages for writing dates and times (also they don’t use AM/PM), I believe that unless you have other requirements, you should try to implement this for English dates and times only. Also you should give an English speaking locale explicitly so it will work independently of the locale setting of your computer or JVM.
I have tried to combine the best parts of answers by Hugo and myself to a duplicate question. Under that duplicate question there are still more java 8 answers. One limitation of the above code is it doesn’t have very strict validation: you will get away with
Feb 13rd
and evenFeb 13stndrdth
.