简单日期格式,解析异常

时间:2015-11-21 20:31:15

标签: java date datetime simpledateformat

使用Android Studio

我正在从facebook上检索一个日期,它是一个字符串" 2015-11-21T17:49:49 + 0000 "

我希望将其变成格式为#34; EEE MMM dd HH:mm:ss Z yyyy "但当然我需要先将其更改为Date对象

试图这样做,我试图将其解析为" EEE-MM-dd' HH:mm:ssZyyyy "但这会导致我的程序崩溃。 " ParseException:Unparseable date:" 2015-11-21T17:49:49 + 0000" (在偏移0处)"

可能是日期附带的T符号吗?或者我使用的格式不正确?

3 个答案:

答案 0 :(得分:4)

您的输入格式需要EEE(不是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(); } )。像,

Sat Nov 21 12:49:49 -0500 2015

输出(因为我在EST中)是

 'data.frame':  20000 obs. of  6 variables:
 $ cal_y  : int  2008 2008 2008 2008 2008 ...
 $ age_y  : int  0 0 0 0 0 0 0 0 0 0 ...
 $ gender : Factor w/ 2 levels "1","2": 1 1 1 1 1 1 1 1 1 1 ...
 $ cal_m  : int  9 7 8 1 6 11 2 10 3 4 ...
 $ n_outcome: int  276 187 164 352 229 250 332 267 348 291 ...
 $ n_atrisk : int  4645 4645 4645 4645 4645 4645 4645 4645 4645 4645 ...

glm(n_outcome ~ factor(cal_y) + factor(cal_m) + gender + offset(log(n_atrisk)),
data = df, family =poisson)

答案 1 :(得分:0)

您也可以使用GregorianCalendar.虽然定义的时间更长,但管理起来更简单。

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());

答案 2 :(得分:0)

您可以使用JodaTime作为外部库。一旦这个库在你的类路径中,你所要做的就是写下这样的东西:

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

然后,您可以将其转换为调用myDate上的Date对象调用toDate()方法。