laasya
laasya

Reputation: 11

SimpleDateFormat parse not honouring timezone

public static void main(String[] args) throws ParseException {
    SimpleDateFormat dt = new SimpleDateFormat("MM dd yy");
    dt.setLenient(false);
    dt.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));
    Date date = dt.parse("05 14 16");
    System.out.println(date);
}

Output: Fri May 13 21:30:00 IST 2016

If i try to use the output it is switching to one day before instead of the correct day.

Is this expected or an issue with the API?

Upvotes: 0

Views: 197

Answers (1)

Jesper
Jesper

Reputation: 206776

This is expected and there is no bug in Java.

Class Date does not contain timezone information. A java.util.Date is nothing more than wrapper for a number of milliseconds since 01-01-1970, 00:00:00 GMT. It does not remember that the string that it was parsed from contained information about a timezone.

When you display a Date, for example by (implicitly) calling toString() on it as you are doing here:

System.out.println(date);

it will be printed in the default timezone of your system, which is IST in your case.

If you want to print it in a certain timezone, then format it using a SimpleDateFormat object, setting the desired timezone on the SimpleDateFormat object. For example:

DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss Z");
df..setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));
System.out.println(df.format(date));

Upvotes: 3

Related Questions