Twitter日期不可解析?

问题描述 投票:13回答:7

我想将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。

干杯,

安迪

java date twitter
7个回答
30
投票

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

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

UPDATE

Roland Illig是对的:SimpleDateFormat依赖于Locale,所以只需使用一个明确的英语语言环境: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
投票

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


2
投票

你不应该有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


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


0
投票

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

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


0
投票

C#你可以这样做

DateTime date = DateTime.ParseExact(dt, "ddd MMM dd HH:mm:ss +0000 yyyy", CultureInfo.InvariantCulture);

© www.soinside.com 2019 - 2024. All rights reserved.