Why isn't this date displayed in GMT?

I see that the GMT time has a constant "Z" as an indication that the time is GMT. However, when I parse the GMT string, it still prints the local time.

Code:

SimpleDateFormat outFormat = new 
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String timeGMT = "2015-05-21T08:42:27.334Z";
try {
    System.out.println("Time GMT>>>>>>"+outFormat.parse(timeGMT));
} catch (ParseException e) {
    e.printStackTrace();
}

      

OUTPUT:

Thu May 21 08:42:27 IST 2015

      

Expected:

Thu May 21 08:42:27 GMT 2015

      

+3


source to share


2 answers


Two questions here.

First, you are using the wrong format for parsing. Your format tells the parser to just look at it Z

as a literal character with no significance.

This means that it will parse it as a local date because it does not treat it Z

as a time zone marker. If you want to be Z

interpreted as a timezone, your format should have X

instead 'Z'

:

    String timeGMT = "2015-05-21T08:42:27.334Z";

    DateFormat f1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    DateFormat f2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");

    Date d1 = f1.parse(timeGMT);
    Date d2 = f2.parse(timeGMT);

    System.out.println(d1);
    System.out.println(d2);

      

I am currently at GMT + 3 and this is the result I get from this:

Thu May 21 08:42:27 IDT 2015
Thu May 21 11:42:27 IDT 2015


As you can see, it d2

is 3 hours ahead, which means it interprets the original time as in GMT.

Another problem is that you are printing the resulting date in the default format. The default format is in your local timezone, so it will print it like mine in the local zone.

To change this, you also need to format the output:

    DateFormat f3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
    f3.setTimeZone(TimeZone.getTimeZone("GMT"));

    System.out.println(f3.format(d2));

      

This gives - for the previous example - the following:

2015-05-21 08:42:27 GMT
+3


source


The Z in your input is NOT a constant constant, but stands for UTC + 00: 00 (alias "GMT"). Remove the apostrophes from the figure around the last character in the pattern. And instead of "Z" use "X" to correctly interpret "Z" as an ISO-8601 marker for UTC + 00: 00 offset.



SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");

      

0


source







All Articles