Monday, August 5, 2013

How will you convert DateTime from one TimeZone to another in Java ?

java.util.Date class is not TimeZone aware, as it does not store any time zone specific information in its object. This is clearly mentioned in the Java Docs for Date Class -

In Date, A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

The internal representation of the time inside Date object remains same for a given time, when we print the date object using System.out.println(date) method then date.toString() method is invoked which prints the date in local TimeZone of the JVM.

Custom TimeZone formatting can be achieved using SimpleDateFormat class.

Calendar instance = Calendar.getInstance();
Date date = instance.getTime();
DateFormat formatter= new SimpleDateFormat("MM/dd/yyyy hh:mm:ss Z");
System.out.println(formatter.format(date)) ;

Thus a given time in milliseconds can be represented in different TimeZone using different TimeZone specific Date formatters.


Always prefer to user Calendar API over Date due to various benefits of Calendar Class - Calendar handles TimeZone information and it correctly measures the duration of a year in milliseconds keeping into account the leap years.

Question : What will be output of the following Java Program ?

Calendar instance = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
Date date = instance.getTime();
System.out.println("date = " + date);
Date date2 = instance.getTime();
System.out.println("date2 = " + date2);

Both the System.out will print the same date value because Date class object is always printed in local TimeZone and changing the TimeZone on Calendar class does not alter the underlying milliseconds value from the epoch time (Since January 1, 1970 00:00:00.000 GMT).

No comments:

Post a Comment

Your comment will be published after review from moderator