Java has couple of ways to handle the concept of date and time. To proceed further let's understand the concept of epoch. Epoch represents time January 1, 1970 00:00:00.000 GMT. It is the milliseconds that has elapsed since epoch. If one is interested in just the time elapsed as long from the ecpoch, once can use System.currentTimeMillis(). The precision value returned by the call depends on the underlying operating system. An operating system with more granular precision(e.g. tens of a second) may not return the right value in milliseconds.
The other two important class that are used to handle date and time are java.util.Date and java.util.Calendar. This is usually a confusion that which one to use in which context. Let's understand the basic major differences between the two before delving further into each one for details.
- Date represents an instance of time. Calendar is more heavyweight as it has knowledge of everything about time instance and zones etc. This makes Calendar class is more complex and heavyweight than Date class.
- The most important use case of calendar is when one is looking for a difference between two time stamps. In modern day client server based applications, it's very common for client and server to be in different timezone. It's important that the difference between two time stamp be done in the same time zone. Also this will take care of any daylight saving issues also.
- Calendar can support different calendar system. The default is Gregorian Calendar. It's the regular English Calendar as we know.
- The current recommendation is to use the Calendar class as far as possible as it is more rich in behavior.
- Calendar and Date both support conversion to each other. One can get Calendar object from Date object and vice versa.
//Converting calendar to date. It's just a time nowDate dt = calendar.getTime();alendar cal = Calendar.getInsta//Converting date to Calendar. Cnce(); cal.setTime(dt);ia Standard Time System.out.println(cal.ge//In my machine prints IndtTimeZone().getDisplayName());
- While transferring the data from database to Java and vice versa, be careful about precision. The database has the concepts of date and time stamp separately whereas in Java its always time stamp. This means a date value when coming from database will get a time associated with it.
- The cheaper way to calculate the elapsed time is to not to use Date or Calendar
long start = System.currentTimeMillis();//Do somethingm.currentTimeMillis(); long elapsedlong end = SysteTime = start -end;
- There is an open source implementation for handling time known as Joda time. Check http://joda-time.sourceforge.net/
Date as mentioned just represents an instant in time, having no other information. It's usually good when one wants to compare elapsed time. To create a date
//This will take the current time from local operating system.Date date = new Date();
Calendar is heavyweight, complex but feature rich. The default implementation of Gregorian Calendar has the information about Timezone including day light saving. Some of the important features of Calendar are:
- Calendar can be set with a lenient/non-lenient mode. From the official javadoc "a date such as "February 942, 1996" will be treated as being equivalent to the 941st day after February 1, 1996. With strict (non-lenient) interpretation, such dates will cause an exception to be thrown. The default is lenient. "
- The midnight is considered as 00:00 and 24:00, which means it is considered as the start of new day.
- For super precisionars, there is a concept of leap second. 1 or 2 seconds are added or subtracted at some intervals either on December 31 0r June 30 or synchronize the clocks with the earths rotation. Last one was done on Dec 31,2008. The bad news, Calendar does not handles this.
While handling date and time issues, we have to take care of time zone issues. This is especially important in case of places having day light saving. Daylight saving rules are governed by local politics and politicians do not care about developers. So it is we developer who has to take care of ourself. Unfortunately there is not single official body taking care of this. The most widely adopted is the TZ database also known as Olson database. This database contains information about all the time zones including day light savings. Java also follows that. Whenever a new version of Java is release, it is shipped with the latest version of TZ database. If you are working with one of the older version of JRE and want to use the latest version of TZ database , you have to follow certain procedure. There is a TZ updater tool for that. For details look herehttp://java.sun.com/javase/timezones/. The data in the JRE is available in the local installation of Java at <JAVA_HOME>\jre\lib\zi. Also the latest list of timezone can be accessed athttp://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Another important issue to consider while using Date or Calendar is to understand from where we are picking the time to create the Date or Calendar object. For example in a multi tier application involving application layer and database layer, deployed on different machine may generate different set of time values. The situation can become worse if application layer is clustered and machines are not synchronized to the right precision level. It's usually a good idea to have a consistent policy regarding time stamp generation in these cases. Some of the strategies that can be deployed are:
- If there is one centralized database to which all the clustered/multiple application are talking to, let the database server generate the time stamp.
- Retrieve the time stamp from a synchronized central server may be using a web service or some sort of remote call.
- Bottom line to be consistent with time stamp generation policy.