What Is The Time Format For This "date": "2014-08-20 00:00:00 -0500"?
I tried converting this date the following way: SimpleDateFormat fromFormat = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss SSSZ'); but I got: java.text.ParseException: Unparseable
Solution 1:
That "-0500" is the offset from UTC, in RFC822 format. You just want Z
, without the SSS
.
The Android SimpleDateFormat
docs have it like this in the table:
- Symbol: Z
- Meaning: time zone (RFC 822)
- Kind: (Time Zone)
- Example:
Z/ZZ/ZZZ
:-0800ZZZZ
:GMT-08:00ZZZZZ
:-08:00
I would also personally specify a locale, as a matter of course: this is a machine-readable format rather than a human-oriented format, so I'd usually specify Locale.US
:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z",
Locale.US);
Stringtext = "2014-08-20 00:00:00 -0500";
System.out.println(format.parse(text));
Solution 2:
The answer by Jon Skeet is correct.
Standard Date-Time Format
Here is some example code showing how to transform your string into compliance with ISO 8601.
String inputRaw = "2014-08-20 00:00:00 -0500";
String input = inputRaw.replaceFirst( " ", "T" ).replaceFirst( " ", "" ); // Replace first SPACE with a 'T', and delete second SPACE.// input is "2014-08-20T00:00:00-0500".
Joda-Time
You can pass that compliant string directly to the constructor of DateTime in Joda-Time. Ditto for the equivalent in the java.time package in Java 8 (inspired by Joda-Time).
DateTimeZonetimeZone= DateTimeZone.forID( "America/Montreal" ); // Specify it rather than have JVM's default applied.DateTimedateTimeMontréal=newDateTime( input, timeZone );
DateTimedateTimeUtc= dateTimeMontréal.withZone( DateTimeZone.UTC );
Dump to console.
System.out.println( "inputRaw: " + inputRaw );
System.out.println( "input: " + input );
System.out.println( "dateTimeMontréal: " + dateTimeMontréal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run…
inputRaw: 2014-08-20 00:00:00 -0500
input: 2014-08-20T00:00:00-0500
dateTimeMontréal: 2014-08-20T01:00:00.000-04:00
dateTimeUtc: 2014-08-20T05:00:00.000Z
Post a Comment for "What Is The Time Format For This "date": "2014-08-20 00:00:00 -0500"?"