简体   繁体   English

简单日期格式,解析异常

[英]Simple Date Format, Parsing Exception

Using Android Studio 使用Android Studio

I'm retrieving a date from facebook, it comes as a string " 2015-11-21T17:49:49+0000 " 我正在从Facebook检索日期,它以字符串“ 2015-11-21T17:49:49 + 0000 ”的形式出现

I wish to turn it into a date with format " EEE MMM dd HH:mm:ss Z yyyy " but of course I need to first change it into a Date object 我希望将其转换为日期为“ EEE MMM dd HH:mm:ss Z yyyy ”的日期,但是我首先需要将其更改为Date对象

Attempting to do that, I've attempted to parse it into " EEE-MM-dd'T'HH:mm:ssZyyyy " but this causes my program to crash. 尝试这样做,我试图将其解析为“ EEE-MM-dd'T'HH:mm:ssZyyyy ”,但这会导致程序崩溃。 "ParseException: Unparseable date: "2015-11-21T17:49:49+0000" (at offset 0)" “ ParseException:无法解析的日期:“ 2015-11-21T17:49:49 + 0000”(偏移量为0)”

Could it be the T symbol coming with the date? 日期是否带有T符号? Or am I using an incorrect format? 还是我使用的格式不正确?

Your input format needs yyyy (not EEE ). 您的输入格式需要yyyy (不是EEE )。 Something like, 就像是,

String in = "2015-11-21T17:49:49+0000";
String fmtIn = "yyyy-MM-dd'T'HH:mm:ssZ";
String fmtOut = "EEE MMM dd HH:mm:ss Z yyyy";
DateFormat sdf = new SimpleDateFormat(fmtIn);
try {
    Date d = sdf.parse(in);
    DateFormat outSDF = new SimpleDateFormat(fmtOut);
    System.out.println(outSDF.format(d));
} catch (ParseException e) {
    e.printStackTrace();
}

Output (because I'm in EST) is 输出(因为我在EST中)是

Sat Nov 21 12:49:49 -0500 2015

You could also use a GregorianCalendar. 您也可以使用GregorianCalendar. Though they take longer to define, they are simpler to manage. 尽管定义时间较长,但管理起来更简单。

GregorianCalendar calendar = new GregorianCalendar();

int year, month, day, hour, minute, second;

//...parse the data and store year, month, day, hour, minute, and second.
//...
//...

//fill in calendar's data.
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1); //month is offset by one (January == 0)
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR, hour); //No need to edit. 12AM is 0, 1AM is 1, 12PM is 12, etc.
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);

//get time in milliseconds since epoch and create Date object.
Date date = new Date(calendar.getTimeInMillis());

You can use JodaTime as external library. 您可以将JodaTime用作外部库。 Once this library is inside your classpath all you have to do is to write something like this: 一旦该库位于您的类路径中,您所需要做的就是编写如下内容:

DateTime myDate = new DateTime("2015-11-21T17:49:49+0000" ); DateTime myDate = new DateTime("2015-11-21T17:49:49+0000" );

You can then convert it into Date object calling toDate() method on myDate. 然后,您可以将其转换为在myDate上调用toDate()方法的Date对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM