Java DateFormat: How to deal with “st”, “nd”, “rd”, “th”?

百般思念 提交于 2021-02-07 07:46:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!