Java uses the java.util.Calendar class to represent and manipulate time information. This document provides some basic background information on how to use this class.
The Calendar class represents time internally as the number of milliseconds that have elapsed since midnight on January 1, 1970, Greenwich Mean Time. This is not a very human-friendly method for representing time, so the Calendar class also uses an array of fields that represent time in units that human users are used to seeing, such as years, months, days, hours, minutes and seconds.
To create a Calendar object that represents the present time, use the syntax
Calendar now = Calendar.getInstance();
To create a Calendar object that represents some other point in time, you have four options. The first option is to use the clear() and set() methods. The clear() method clears all the current field values for a Calendar object. There are a number of multi-parameter set methods in the Calendar class that can be used to set several fields at once. Often, one of these will be available to allow you to express the time you want to express. For example, if we wanted to make a Calendar object to represent 8:32 PM on June 26, 2015, we would do
Calendar c = Calendar.getInstance(); c.clear(); c.set(2015,Calendar.JUNE,26,20,32);
The second option is to convert a text representation of your date to a Calendar object. I will cover that method in detail below in the section on converting Calendars to and from Strings.
A third method is to modify an existing Calendar object to give it the characteristics you want. This is done by using the Calendar class's two parameter set() method. This method takes two parameters, a field specifier and a value. The field specifier is an integer constant that identifies the specific field we wish to set - you can find a list of these field specifiers in the documentation for the Calendar class. For example, to create a Calendar object that represents 8:32 PM on June 26, 2015, we would do
Calendar c = Calendar.getInstance(); c.clear(); c.set(Calendar.YEAR,2015); c.set(Calendar.MONTH,Calendar.JUNE); c.set(Calendar.DAY_OF_MONTH,26); c.set(Calendar.HOUR,8); c.set(Calendar.AM_PM,Calendar.PM); c.set(Calendar.MINUTE,32);
A fourth method is to use the use the add() method to modify a Calendar object starting from a reference time. Similar to the set() method, the add() method takes two parameters, a field specifier and an amount to add to that field (the amount can be positive or negative). This is most useful in applications when the reference time is now and you want to create a Calendar object that represents a time that can be expressed simply relative to the reference time. For example, suppose we are writing an application to run a library and that books are due 14 days after they are checked out. To create a Calendar object that represents the due date we would do
Calendar due = Calendar.getInstance(); due.add(Calendar.DATE,14);
The add() method automatically takes care of rolling over fields as needed. Thus, if today were June 25 and we added 14 days we would get July 9.
In various places Java will require that you provide a java.util.Date object to represent a time. You can convert Calendar objects to and from Date objects by using the Calendar class's getTime() and setTime() methods.
For example, if you had a Calendar object c you could do the following:
Date d = c.getTime(); Calendar other = Calendar.getInstance(); other.setTime(d);
You can also make a copy of a Calendar object by using the clone() method. Since clone() returns an Object, you will have to typecast the returned object to Calendar.
public Calendar makeLaterHours(Calendar original,int hoursLater)
{
Calendar copy = (Calendar) original.clone();
copy.add(Calendar.HOUR,hoursLater);
return copy;
}
You can easily compare Calendar objects by using the after(), before(), equals(), or compareTo() methods. For example, here is a method that finds the later of two time objects.
public Calendar findLater(Calendar one, Calendar two)
{
if(one.after(two))
return one;
else
return two;
}
To compute the interval in time between two Calendar objects you can use their getTimeInMillis() methods to get the internal representations of the two times in milliseconds and do some simple arithmetic to convert the difference to the time unit of your choice. For example, to compute the difference in hours between two times we can do
public int spanInHours(Calendar one,Calendar two)
{
int differenceInMillis = two.getTimeInMillis() - one.getTimeInMillis();
return differenceInMillis/(1000*60*60);
}
(Note that this function rounds the difference in hours down.)
The java.text.DateFormat class is used to convert time information stored in Calendar objects into user-friendly text. Because there are a variety of different ways that the same time can be represented, the DateFormat class allows you to specify a formatting style for the conversion. The formatting style can be either DateFormat.FULL, DateFormat.LONG, DateFormat.MEDIUM, or DateFormat.SHORT. Longer formats spell out months fully, while shorter formats use more abbreviated forms.
To construct a string representation for a Calendar object c you use the DateFormat class's format() method. format() takes a single parameter of type java.util.Date. You can get a Date object from a Calendar object by using the Calendar's getTime() method.
For example, to convert a Calendar object c to a String using the LONG format you would do
DateFormat df = DateFormat.getInstance(DateFormat.LONG); String str = df.format(c.getTime());
DateFormats also allow you to set a locale for the conversion. In different countries in the world time is represented in different ways. To produce a text representation that is appropriate for a particular country, you set the DateFormat object to use the Locale for that country and then do the conversion.
DateFormat chinaDF = DateFormat.getInstance(DateFormat.LONG,Locale.CHINA); String str = df.format(c.getTime());
The DateFormat class does not give you full control over the conversion to text. To get more complete control over the conversion process you can use a subclass of the DateFormat class, the java.text.SimpleDateFormat class. The SimpleDateFormat class has a constructor that allows you to specify a pattern string that will be used for the conversion. In the pattern string you specify which fields of the time you want to have show up in the formatted time string and in what order. For example, to construct a String with only the month and day you would use the format string "MMMM d".
SimpleDateFormat df = new SimpleDateFormat("MMMM d");
String str = df.format(c.getTime());
In this format string the M stands for 'month' and d for 'date'. The number of repetitions of each letter is also significant - 4 Ms means to write the name of the month out in long form as a text name, while the single d means to write the day out using at least one digit. The rules for formatting strings are quite involved, and give you considerable control in how the time will be rendered as a String. See the documentation for the java.text.SimpleDateFormat class for more details
SimpleDateFormat can also be used for parsing time values from Strings. The approach here is to construct a formatting string that matches the format you expect to receive your time information in. Using that formatting string you construct a SimpleDateFormat object and then call that object's parse() method to parse the input string. For example, suppose you are working on an application in which users will typically enter date information in the form "06/25/2015". The following code shows how to convert a date string str into a Calendar object.
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar result = Calendar.getInstance();
result.setTime(df.parse(str));