Thursday, December 8, 2011

Java Date, Calendar and Time API - Tutorial


The Calendar class’ date/time API is a nifty tool for accurately manipulating date and time values without too much stress or custom coding. It provides direct support for time based objects. This article gives a few examples how this API can be used. .

The class java.util.Date was the first implementation which was used for manipulating dates. The class java.util.Calendar was added in Java 1.1 and provides simplified access to storing and manipulating dates.
It is recommended to use Calendar if possible. In reality you have to convert frequently from Date to Calendar and vice versa, e.g. during database access you often get a java.sql.Date object. The following explains how to use Calendar and how to convert Dates into Calendar.

It also offers a set of methods for converting and manipulating temporal information. In addition to retrieving the current date and time, the Calendar class also provides an API for date arithmetic. The API takes care of the numerous minor adjustments that have to be made when adding and subtracting intervals to date and time values.

Calendar’s built-in date/time arithmetic API is extremely useful. For example, consider the number of lines of code that go into calculating what the date will be five months from today. Try doing this yourself — you need to know the number of days in the current month and in the intervening months, as well as make end-of-year and leap year modifications to arrive at an accurate final result. These kinds of calculations are fairly complex and are quite easy to get wrong — especially if you’re a novice developer.


To format a date you can use the class SimpleDateFormat. For example to get today's date in the 'dd/MM/yy' format you can use:
  DateFormat df = new SimpleDateFormat("dd/MM/yy"); 
  String formattedDate = df.format(new Date());

To format the date in in the format 'yyyy/MM/dd' you can use.
  DateFormat df = new SimpleDateFormat("yyyy/MM/dd"); 
  String formattedDate = df.format(theDate);

Table 1. Calendar field access

FieldExplanationCalendar.YEAR Identifies the year
Calendar.MONTH Identifies the month
Calendar.DAY_OF_MONTH Identifies the day
Calendar.HOUR Identifies the hour
Calendar.MINUTE Identifies the minute
Calendar.SECOND Identifies the second

Tutorial is on GitHub: Timer Tutorial