简体   繁体   中英

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?

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM