Calculate, customize, and parse dates with Java Date and Calendar classes

Manipulating date information is integral to many programming tasks. And with Java's Date and Calendar classes, you can create, format, and parse dates to your heart's content. Run through our examples and learn how to put these classes to work.

Java Calendar, Date, and DateFormat classes comprise a basic, yet critical, part of the Java spec. Dates are a crucial aspect of business logic calculations. All developers should be able to calculate future dates, customize date formats, and parse text dates into date objects. In this first of two articles, we'll provide an overview of dates, date formatting, date parsing, and date calculations.

We're going to cover these classes:
  • The concrete class java.util.Date
  • The abstract class java.text.DateFormat and one of its concrete subclasses, java.text.SimpleDateFormat
  • The abstract class java.util.Calendar and one of its concrete subclasses, java.util.GregorianCalendar

Concrete classes can be instantiated, but abstract classes cannot be instatiated. You must first implement a concrete subclass of the abstract class.

The Date class has evolved since Java Development Kit (JDK) 1.0., when it included several methods for getting and setting parts of a date, such as the month, day, or year. These methods are now deprecated and have evolved into the Calendar class, which we’ll discuss further in this article. This evolution was meant to better handle internationalized formatting of dates. As of JDK 1.1, the Date class is really just a wrapper class around a long value representing the number of milliseconds since or before 00:00:00 GMT Jan. 1, 1970.

Creating a date
Let’s look at a simple example of creating a date using the system clock’s current date and time and returning a long value. This is often referred to as the system time of the host environment of the Java Virtual Machine (JVM).
import java.util.Date;
public class DateExample1 {
    public static void main(String[] args) {
        // Get the system date/time
        Date date = new Date();

On Saturday, Sept. 29, 2001, at about 6:50 P.M., the example printed to the system the output of 1001803809710. What’s notable in this example is the creation of a date using the Date constructor, which doesn’t accept any parameters. This constructor internally used the method System.currentTimeMillis() to get the date from the system.

So now we know how to get the number of milliseconds since Jan. 1, 1970. How do we display the date in a format that a user can understand? This is where the class java.text.SimpleDateFormat and its abstract superclass java.text.DateFormat can help.

Customized formatting of dates
Suppose we want to format dates in a customized way, such as Saturday-September-29-2001. The following example illustrates how to accomplish this:
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample2 {
    public static void main(String[] args) {
        SimpleDateFormat bartDateFormat =
            new SimpleDateFormat("EEEE-MMMM-dd-yyyy");
        Date date = new Date();

By passing in the format string “EEEE-MMMM-dd-yyyy” to the constructor of SimpleDateFormat, we were able to specify the desired format. As you can see, ASCII letters in the format string tell the formatter what portion of the date to print next. EEEE is the day, MMMM is the month, dd is the day of the month, and yyyy is the year. The number of letters controls how the date is formatted. Passing in “EE-MM-dd-yy” would have produced Sat-09-29-01. See Sun’s Web site for complete instructions on date formatting options.

Parsing a text date into a date object
Suppose we have a text string containing a formatted date, and we want to parse the string and create a date object from the text date. We’ll use the SimpleDateFormat class again with a format string of “MM-dd-yyyy”, but this time, we’ll use the format string to parse rather than generate a text date. Our example, shown in Listing A, parses the text string “9-29-2001” and creates a date that has a long value of 1001736000000.

Using standard date formatters
Now that we can generate and parse custom date formats, let’s look at using built-in formatters. The method DateFormat.getDateTimeInstance() gives us several options for getting standard date formatters. In Listing B, we get four built-in date formatters. The versions include a short, medium, long, and full date format.

Notice that we pass in two values to each call to getDateTimeInstance. The first parameter is the date style, and the second is the time style. Both are the primitive data type int. For readability, we use the constants supplied with the DateFormat class: SHORT, MEDIUM, LONG, and FULL. For more methods and options to get time and date formatters, see the explanation on Sun’s Web site.

Running our example prints the following to the standard output:
9/29/01 8:44 PM
Sep 29, 2001 8:44:45 PM
September 29, 2001 8:44:45 PM EDT
Saturday, September 29, 2001 8:44:45 PM EDT

The Calendar class
We can now format and create dates, but how do we set and get specific parts of a date such as the hour, the day, or the minute? And how do we add and subtract values to these parts of a date? The answer is to use the Calendar class. As we mentioned earlier, the methods in the Calendar class replace the deprecated methods of the Date class.

Suppose you want to set, get, and manipulate portions of a date, such as the day of the month or the day of the week. To illustrate this, we’ll use the concrete subclass java.util.GregorianCalendar. Consider the example in Listing C, which calculates the next 10 Friday the 13ths.

The interesting calls made in the example are:

        cal.add(GregorianCalendar.DAY_OF_MONTH, 7);

The set method allowed us to adjust our date to Friday by simply setting the day of the week field. Notice here that we used the constants DAY_OF_WEEK and FRIDAY for readability. The add method allowed us to add days to the day of the month. All of the complexities of leap year are handled by this method.

The output of the example is:
System Date: Saturday, September 29, 2001
After Setting Day of Week to Friday: Friday, September 28, 2001
Friday, September 13, 2002
Friday, December 13, 2002
Friday, June 13, 2003
Friday, February 13, 2004
Friday, August 13, 2004
Friday, May 13, 2005
Friday, January 13, 2006
Friday, October 13, 2006
Friday, April 13, 2007
Friday, July 13, 2007
Friday, June 13, 2008

Time is in your hands
With these examples of the Date and Calendar classes, you should be able to construct a variety of methods using java.util.Date, java.text.SimpleDateFormat, and java.util.GregorianCalendar.

In the next article, we'll discuss more advanced Date and Calendar class techniques, including time zones and internationalized formatting. We'll also look at the differences between the date classes java.sql.Date and java.util.Date.

Stupid date tricks
What things have you tried to do in Java relating to dates or the calendar? Do you have any tips or techniques to share? Send us an e-mail with your experiences and suggestions or post a comment below.


Editor's Picks