问题
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
.
回答1:
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);
回答2:
Any literals that are not part of the DateFormat parser can be placed between '
. Like 'th', 'T','nd','st'
回答3:
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.
回答4:
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.
来源:https://stackoverflow.com/questions/17485907/java-dateformat-how-to-deal-with-st-nd-rd-th