Twitter日期无法解析?

13

我想把Twitter响应中的日期字符串转换为日期对象,但我总是得到一个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。

谢谢,

Andi

6个回答

31

你的格式化字符串对我有效,看这里:

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"));          
    }

输出:

2010年12月03日星期五18:26:07格林威治标准时间

更新

Roland Illig是正确的: SimpleDateFormat依赖于语言环境,因此只需使用明确的英语语言环境: SimpleDateFormat sf = new SimpleDateFormat(TWITTER,Locale.ENGLISH);


5
这对我有效;)
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);
}

4
也许你所在的地区不认识“Tue”这个星期几,比如德国。尝试使用接受“Locale”参数的“SimpleDateFormat”构造函数,并将其传递给“Locale.ROOT”。

2

1
Java 1.4是很久以前的版本了... :) 更新后的链接是http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html。 - robert_x44

1
将 Twitter 日期转换的函数:

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。

为了帮助 OP 解决当前的问题,可以在回答中添加一些解释说明。 - ρяσѕρєя K

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接