我需要用 Java 解析格式为“2010 年 1 月 10 日”的日期。我该怎么做?
如何处理 ordinal indicators 、st
、nd
、rd
或 th
尾随天数?
最佳答案
这个有效:
String s = "January 10th, 2010";
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
System.out.println("" + dateFormat.parse(s.replaceAll("(?:st|nd|rd|th),", "")));
但是你需要确保你使用的是正确的Locale
正确解析月份名称。
我知道您可以在 SimpleDateFormat
中包含一般文本图案。然而,在这种情况下,文本取决于信息,实际上与解析过程无关。
这实际上是我能想到的最简单的解决方案。但我很乐意被证明是错误的。
您可以通过执行与此类似的操作来避免其中一条评论中暴露的陷阱:
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
。
关于java - 在 Java 中解析格式为 "January 10th, 2010"的日期? (带序号指示符,st|nd|rd|th),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4722289/