用Java解析格式“2010年1月10日”的日期? (有序数指标,st | nd | rd | th)
我需要用Java解析格式“2010年1月10日”的日期。 我怎样才能做到这一点?
如何处理序数指标 , 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
模式中包含一般文本。 但是在这种情况下,文本取决于信息,实际上与解析过程无关。
这实际上是我能想到的最简单的解决方案。 但我希望被certificate是错的。
您可以通过执行与此类似的操作来避免在其中一条评论中暴露的陷阱:
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
。
您可以在SimpleDateFormat中将nd
等设置为文字。 您可以定义所需的四种格式并尝试它们。 从th
一个开始,因为我猜这会更频繁地发生。 如果ParseException
失败,请尝试下一个。 如果全部失败,则抛出ParseException。 这里的代码只是一个概念。 在现实生活中,您可能不会每次都生成新格式,并且可能会考虑线程安全性。
public static Date hoolaHoop(final String dateText) throws ParseException { ParseException pe=null; String[] sss={"th","nd","rd","st"}; for (String special:sss) { SimpleDateFormat sdf=new SimpleDateFormat("MMMM d'"+special+",' yyyy"); try{ return sdf.parse(dateText); } catch (ParseException e) { // remember for throwing later pe=e; } } throw pe; } public static void main (String[] args) throws java.lang.Exception { String[] dateText={"January 10th, 2010","January 1st, 2010","January 2nd, 2010",""}; for (String dt:dateText) {System.out.println(hoolaHoop(dt))}; }
输出:
2010年1月10日00:00:00 GMT
2010年1月1日00:00:00 GMT 2010
2010年1月2日星期六00:00:00 GMT
线程“main”中的exceptionjava.text.ParseException:Unparseable date:“”
"th","nd","rd","st"
当然只适用于具有英语语言的语言环境。 记住这一点。 在法国,我想"re","nd"
等。
这是另一种简单的方法,但需要包含apache commons jar 。
import org.apache.commons.lang.time.*; String s = "January 10th, 2010"; String[] freakyFormat = {"MMM dd'st,' yyyy","MMM dd'nd,' yyyy","MMM dd'th,' yyyy","MMM dd'rd,' yyyy"}; DateUtils du = new DateUtils(); System.out.println("" + du.parseDate(s,freakyFormat));