我需要用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
模式。但是在这种情况下,文本取决于信息,实际上与解析过程无关。
这实际上是我能想到的最简单的解决方案。但我希望被证明是错的。
您可以通过执行与此类似的操作来避免在其中一条评论中暴露的陷阱:
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
例如。
你可以设置 nd
等作为文字中的文字 的SimpleDateFormat。您可以定义所需的四种格式并尝试它们。从...开始 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”中的异常java.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));