Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy , derived from this milliseconds value.
Use "zzz" instead of "ZZZ": "Z" is the symbol for an RFC822 time zone. DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); Having said that, my standard advice on date/time stuff is to use Joda Time, which is an altogether better API.
The T is just a literal to separate the date from the time, and the Z means “zero hour offset” also known as “Zulu time” (UTC). If your strings always have a “Z” you can use: SimpleDateFormat format = new SimpleDateFormat( “yyyy-MM-dd'T'HH:mm:ss).
You haven't set the timezone only added a Z
to the end of the date/time, so it will look like a GMT date/time but this doesn't change the value.
Set the timezone to GMT and it will be correct.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
'T'
and 'Z'
are considered here as constants. You need to pass Z
without the quotes. Moreover you need to specify the timezone in the input string.
Example : 2013-09-29T18:46:19-0700
And the format as "yyyy-MM-dd'T'HH:mm:ssZ"
From ISO 8601 String to Java Date Object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
sdf.parse("2013-09-29T18:46:19Z"); //prints-> Mon Sep 30 02:46:19 CST 2013
if you don't set TimeZone.getTimeZone("GMT")
then it will output Sun Sep 29 18:46:19 CST 2013
From Java Date Object to ISO 8601 String
And to convert Date
object to ISO 8601 Standard (yyyy-MM-dd'T'HH:mm:ss'Z'
) use following code
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(sdf.format(new Date())); //-prints-> 2015-01-22T03:23:26Z
Also note that without ' '
at Z yyyy-MM-dd'T'HH:mm:ssZ
prints 2015-01-22T03:41:02+0000
IF you want to handle 'standard' JSON representation of the Date then better to use this pattern: "yyyy-MM-dd'T'HH:mm:ssX"
.
Notice the X
on the end. It will handle timezones in ISO 8601 standard, and ISO 8601 is exactly what produces this statement in Javascript new Date().toJSON()
Comparing to other answers it has some benefits:
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With