5

How can I parse a string like this using some DateFormat?

Wednesday, 24th July

As far as I can tell there's nothing in SimpleDateFormat.

JREN
  • 3,572
  • 3
  • 27
  • 45
Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
  • 6
    Please take some time to write your abbreviations out fully. Writing AFAICT instead of "As far as I can tell" is just lazy and makes it harder for the people trying to help you to actually help you because not everyone knows what it means. – JREN Jul 05 '13 at 09:50
  • Okay, I'll try to remember. But it's so notoriously known that it can be considered a language construct rather than an abbreviation, unlike eg. JVM. – Ondra Žižka Jul 05 '13 at 20:53
  • And BTW it's an acronym, FYI ;-) – Ondra Žižka Jul 05 '13 at 20:59
  • I had to google it and my comment got 5 upvotes, so that should be a reasonable indication that I'm not the only one ;) please keep it in mind for the next time. It takes less time and effort to write your words out fully than it does to go and look up what it means. – JREN Jul 05 '13 at 23:22
  • The `java.util` Date-Time API and their formatting API, `SimpleDateFormat` are outdated and error-prone. It is recommended to stop using them completely and switch to the [modern Date-Time API](https://www.oracle.com/technical-resources/articles/java/jf14-Date-Time.html). Check [this page](https://stackoverflow.com/q/67617220/10819573) to learn how to solve it using the modern Date-Time API. – Arvind Kumar Avinash May 28 '21 at 21:14

4 Answers4

2

try this

String str = "Wednesday, 24th July";
str = str.replaceAll("(\\d\\d)..", "$1") + " " + Calendar.getInstance().get(Calendar.YEAR);
Date date = new SimpleDateFormat("EEEE, dd MMMM yyyy", Locale.US).parse(str);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

Any literals that are not part of the DateFormat parser can be placed between '. Like 'th', 'T','nd','st'

sadhu
  • 1,429
  • 8
  • 14
0

You are trying to parse something which is not a date, but is a day instead. Evgeniy Dorofeev put a nice way to solve this. But if you are really interested in parsing a day, you should create your own class Day and supported DayFormat classes.

blackSmith
  • 3,054
  • 1
  • 20
  • 37
-1

Best idea I have on top of my head is to try with four different patterns:

EEEE, d'st' MMMM
EEEE, d'nd' MMMM
...

Though if the rest of the format is fixed, you can probably roll your own parser fairly easy.

Slartibartfast
  • 8,735
  • 6
  • 41
  • 45