SimpleDateFormat add some minutes

回眸只為那壹抹淺笑 提交于 2019-12-19 10:06:14

问题


Im trying parse a date from a JSONObject

"timcre_not":"2013-12-11 21:25:04.800842+01"

and I parse with

mDate = new SimpleDateFormat("y-M-d h:m:s.SSSSSSZZ",  
                          Locale.ENGLISH).parse(json.getString("timcre_not"));

but the mDate value is:

Wed Dec 11 21:38:24 CET 2013

What is happening?


回答1:


The answer by treeno is correct.

Joda-Time

As an alternative, you can use the third-party open-source Joda-Time. Joda-Time is often used to supplant the java.util.Date & Calendar classes found in Java (and Android).

ISO 8601

The string you have is loosely in ISO 8601 format. Replace that SPACE with a LATIN CAPITAL LETTER T "T" character to get a strict ISO 8601 format.

Joda-Time's DateTime class accepts an ISO 8601 string directly to its constructor. One catch: As with java.util.Date, a DateTime tracks only to the millisecond not microsecond. But in Joda-Time, rather than throw an error, the DateTime merely truncates (ignores) the extra (beyond 3) decimal places.

Example Code

Here is some example code using Joda-Time 2.3 and Java 8.

String input = "2013-12-11 21:25:04.800842+01";
String string = input.replace( " ", "T" ); // Replace SPACE with "T" for strict ISO 8601 format.

DateTime dateTimeUtc = new DateTime( string, DateTimeZone.UTC );

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeParis = new DateTime( string, timeZone );

Dump to console…

System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeParis: " + dateTimeParis );

When run…

dateTimeUtc: 2013-12-11T20:25:04.800Z
dateTimeParis: 2013-12-11T21:25:04.800+01:00

Java 8

I tried using the new java.time.* classes in Java 8 to parse your string.

ZonedDateTime zonedDateTime = ZonedDateTime.parse( string );

Unfortunately, the parser did not tolerate the time zone offset being the shortened +01. I tried the longer +01:00 and it worked. This seems to be a flaw in the Java implementation, not your string. The shortened offset is allowed in ISO 8601. While both I and RFC 3339 (a near-profile of ISO 8601) prefer using the longer +01:00, the ISO standard doe allow it and so should the java.time.* classes. I filed Bug Id: 9009717 with Oracle.

Get Better Data

If possible, suggest to the source of your date that they use the more strict and common ISO 8601 format including:

  • Use the letter "T" in place of SPACE
  • Longer time zone offset, "+01:00" rather than "+01"



回答2:


This should be the solution: Date object SimpleDateFormat not parsing timestamp string correctly in Java (Android) environment

SimpleDateFormat cannot take microseconds, only milliseconds.



来源:https://stackoverflow.com/questions/21162083/simpledateformat-add-some-minutes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!