2013-09-21 110 views
1

运行这个程序:为什么SimpleDateFormat无法解析日期字符串中的weekday?

import java.text.*; 
import java.util.*; 
public class xx { 
    public static void main(String[] args) throws Exception { 
     final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); 
     format.setLenient(false); 
     format.parse("Tue, 16 Jan 2010 04:41:09 -0000"); 
    } 
} 

给出了这样的结果(java version "1.7.0_17"):

Exception in thread "main" java.text.ParseException: Unparseable date: "Tue, 16 Jan 2010 04:41:09 -0000" 
at java.text.DateFormat.parse(DateFormat.java:357) 
at xx.main(xx.java:7) 

看来,当设置为非宽松模式下,Tue,前缀是什么无法解析。

问题是,为什么EEE,未能匹配日期字符串的Tue,前缀?

回答

6

那是因为1月16日不是星期二,而是星期六。

public static void main(String args[]) throws ParseException { 
    final SimpleDateFormat format = new SimpleDateFormat(
      "EEE, dd MMM yyyy HH:mm:ss Z", Locale.US); 
    format.setLenient(false); 
    format.parse("Sat, 16 Jan 2010 04:41:09 -0000"); 
} 

工作得很好。

+0

D'oh!谢谢。那么简单:) – Archie

+1

请告诉我你不知道你的头顶? (Stolen from [here](http://stackoverflow.com/a/6841479/1240557);)) – kryger