Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SimpleDateFormat Wrong Timezone after parsing

Why: When I give input date string with GMT timezone, SimpleDateFormat parses it and outputs EET timezone?

public static String DATE_FORMAT="dd MMM yyyy hh:mm:ss z";
public static String CURRENT_DATE_STRING ="31 October 2011 11:19:56 GMT";
...
SimpleDateFormat simpleDateFormat =  new SimpleDateFormat(DATE_FORMAT, Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(simpleDateFormat.parseObject(CURRENT_DATE_STRING));

And the output is:

Mon Oct 31 13:19:56 EET 2011

rather than

Mon Oct 31 13:19:56 GMT 2011

like image 958
IgorDiy Avatar asked Oct 31 '11 10:10

IgorDiy


People also ask

What is the default TimeZone for SimpleDateFormat?

If not specified otherwise, the time zone associated with a new SimpleDateFormat is the default one, corresponding to the time zone reported by the operating system. Consider the following code: SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); Date date = sdf.

What is locale in SimpleDateFormat?

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date → text), parsing (text → date), and normalization. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting.

How do I change TimeZone in SimpleDateFormat?

SimpleDateFormat myDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); myDate. setTimeZone(TimeZone. getTimeZone("UTC")); Date newDate = myDate. parse("2010-05-23T09:01:02");

How do you change date format to MM DD YYYY in Java?

String pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);


1 Answers

You're printing out the result of Date.toString(). A Date doesn't have any concept of a timezone - it's just the number of milliseconds since the UTC Unix epoch. Date.toString() always uses the system default time zone.

Note that you shouldn't be expecting "Mon Oct 31 13:19:56 GMT 2011" given that you've given a time which specifies a GMT hour of 11, not 13.

If you want to use a specific time zone for printing, you should use another DateFormat for the printing, rather than using Date.toString(). (Date.toString() keeps causing confusion like this; it's really unfortunate.)

like image 136
Jon Skeet Avatar answered Sep 21 '22 06:09

Jon Skeet