解析格式“2010 年 1 月 10 日"的日期在爪哇?(带序数指标,st|nd|rd|th)

解析格式“2010 年 1 月 10 日

问题描述:

我需要在 Java 中解析2010 年 1 月 10 日"格式的日期.我该怎么做?

I need to parse the dates of the format "January 10th, 2010" in Java. How can I do this?

如何处理序数指标stndrdth 尾随日期?

How to handle the ordinal indicators, the st, nd, rd, or th trailing the day number?

这有效:

String s = "January 10th, 2010";
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
System.out.println("" + dateFormat.parse(s.replaceAll("(?:st|nd|rd|th),", "")));

但您需要确保使用正确的Locale 正确解析月份名称.

but you need to make sure you are using the right Locale to properly parse the month name.

我知道您可以在 SimpleDateFormat 模式.然而,在这种情况下,文本取决于信息,实际上与解析过程无关.

I know you can include general texts inside the SimpleDateFormat pattern. However in this case the text is dependent on the info and is actually not relevant to the parsing process.

这实际上是我能想到的最简单的解决方案.但我很想被证明是错误的.

This is actually the simplest solution I can think of. But I would love to be shown wrong.

您可以通过执行以下类似操作来避免其中一条评论中暴露的陷阱:

You can avoid the pitfalls exposed in one of the comments by doing something similar to this:

String s = "January 10th, 2010";
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
System.out.println("" + dateFormat.parse(s.replaceAll("(?<= \d+)(?:st|nd|rd|th),(?= \d+$)", "")));

例如,这将允许您不匹配 Jath,uary 10 2010.

This will allow you to not match Jath,uary 10 2010 for example.