Twitter日期不可解析?

我想将Twitter响应中的日期字符串转换为Date对象,但我总是得到ParseException,我看不到错误!?!

输入字符串:Thu Dec 23 18:26:07 +0000 2010

SimpleDateFormat模式:

 EEE MMM dd HH:mm:ss ZZZZZ yyyy 

方法:

 public static Date getTwitterDate(String date) { SimpleDateFormat sf = new SimpleDateFormat(TWITTER); sf.setLenient(true); Date twitterDate = null; try { twitterDate = sf.parse(date); } catch (Exception e) {} return twitterDate; } 

我也试过这个: http : //friendpaste.com/2IaKdlT3Zat4ANwdAhxAmZ,但结果相同。

我在Mac OS X上使用Java 1.6。

干杯,

和我

您的格式字符串适用于我,请参阅:

 public static Date getTwitterDate(String date) throws ParseException { final String TWITTER="EEE MMM dd HH:mm:ss ZZZZZ yyyy"; SimpleDateFormat sf = new SimpleDateFormat(TWITTER); sf.setLenient(true); return sf.parse(date); } public static void main (String[] args) throws java.lang.Exception { System.out.println(getTwitterDate("Thu Dec 3 18:26:07 +0000 2010")); } 

输出:

星期五12月03日18:26:07 GMT 2010

请参阅: http : //ideone.com/jdGKC

UPDATE

Roland Illig是对的:SimpleDateFormat是依赖于Locale的,所以只需使用一个显式的英语语言环境: SimpleDateFormat sf = new SimpleDateFormat(TWITTER,Locale.ENGLISH);

这对我有用;)

 public static Date getTwitterDate(String date) throws ParseException { final String TWITTER = "EEE, dd MMM yyyy HH:mm:ss Z"; SimpleDateFormat sf = new SimpleDateFormat(TWITTER, Locale.ENGLISH); sf.setLenient(true); return sf.parse(date); } 

也许你所在的地方’周二’不是公认的星期几,例如德语。 尝试使用’SimpleDateFormat’构造函数接受’Locale’作为参数,并将其传递给’Locale.ROOT’。

您不应该使用ZZZZZ而只能使用Z作为时区。

有关详细信息,请参阅http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html中的示例。

EEE, d MMM yyyy HH:mm:ss Z > Wed, 4 Jul 2001 12:08:56 -0700

转换Twitter日期的function:

 String old_date="Thu Jul 05 22:15:04 GMT+05:30 2012"; private String Convert_Twitter_Date(String old_date) { SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss"); SimpleDateFormat old = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy",Locale.ENGLISH); old.setLenient(true); Date date = null; try { date = old.parse(old_date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sdf.format(date); } 

输出格式如:05-Jul-2012 11:54:30

SimpleDateFormat不是线程安全的。 “EEE MMM dd HH:mm:ss ZZZZZ yyyy”正在我们的应用程序中工作,但在一小部分案例中失败了。 我们终于意识到问题来自使用SimpleDateFormat的相同实例的多个线程。

以下是一种解决方法: http : //www.codefutures.com/weblog/andygrove/2007/10/simpledateformat-and-thread-safety.html