Java.util package is a utility package that contains classes useful for working with groups of object. It also contains Java Date class. Java Date class is used to work with dates and times and it allows you to work with date and time independent of the system.

Date can be created by mentioning the number of milliseconds from the epoch (midnight GMT, January 1st, 1970) or the year, month, date, and, optionally, the hour, minute, and second. Years are specified as the number of years since 1900.

Java Date class has many constructors. If you want the Date to be initialized to the current time and date, you should call Java Date constructor with no arguments. Java Date class has many instance methods tat can be used to get and set the various date and time fields, to compare dates and times, and to convert dates to and from string representations.

If you are using Java 1.1, you should know that many of the date methods have been deprecated. So do read documentation (Java Doc) before using any method.

Java Date class implements Cloneable, Comparable and Serializable interfaces.

I will provide you method summary of Java Date class. You will note that many methods of Date class have been deprecated. It has been largely replaced by the java.util.Calendar class. But still, Java Date class include a few useful methods.

Java Date Conventions and Representations

Java Date class methods, that accept or return year, month, date, hours, minutes, and seconds values, the following conventions and representations are used:

  • A year is represented by the integer y 2000.
  • A month is represented by an integer form 0 to 11; 0 is January, 1 is February, 2 is March, 3 is April, 4 is May, 5 is June, 6 is July, 7 is August, 8 is September, 9 is October, 10 is November and 11 is December.
  • A day of month is represented in normal way, by an integer from 1 to 31.
  • An hour is represented by an integer from 0 to 23. 12AM is hour 0.
  • A minute is represented by an integer from 0 to 59 in the usual manner.
  • A second is represented by an integer from 0 to 61. The values 60 and 61 are used for leap calculations.


Java Date Constructors

While creating an instance of Date class, you have many choices. These choices are provided by the Date class constructors. Java Date class has 6 constructors, although 4 of them are deprecated.

  • Date()

    Initializes a Date object to represent the time at which it was allocated, measured to the nearest millisecond.

  • Date(int year, int month, int date)

    It is deprecated and is replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).

  • Date(int year, int month, int date, int hrs, int min)

    It is deprecatedand is replaced by Calendar.set(year + 1900, month, date, hrs, min) or GregorianCalendar(year + 1900, month, date, hrs, min).

  • Date(int year, int month, int date, int hrs, int min, int sec)

    It is deprecated and is replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec).

  • Date(long date)

    Initializes a Date object to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

  • Date(String s)

    It is deprecated and is replaced by DateFormat.parse(String s).

    Example:

    Java Code:
    Date midnight_jan2_1970 = new Date(24L*60L*60L*1000L);
    // creating a Date object for a time
    // giving no of milliseconds since midnight, January 1, 1970, Greenwich Meantime 
    // to the constructor
    System.out.println("Java Date: " + midnight_jan2_1970);
    Output:

    Java Date: Fri Jan 02 01:00:00 CET 1970
    In the above example, we used Date(long date) constructor of the Date class. We wanted to initialize the object with a specific date so had to mention no of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

    Example:

    Java Code:
    Date new_date = new Date();
    System.out.println("New Date: " + new_date);
    Output:

    New Date: Sat Aug 04 17:54:04 CEST 2007
    In the above example, I used Date() constructor to create a date object that is initialized to the current date and time.


Java Date Methods

Following methods are available in Java Date class:

  • after()

    after() function is used to test if this date is after the specified date. It returns boolean value. Signature is: boolean after(Date when)

    Example:

    Java Code:
    Date midnight_jan2_1970 = new Date(24L*60L*60L*1000L);
    Date new_date = new Date();
    System.out.println("Calculated Date: " + midnight_jan2_1970);
    System.out.println("New Date: " + new_date);
    
    if (midnight_jan2_1970.after(new_date)) {
        System.out.println("Calculated Date is after the New date.");
    }
    else
    {
        System.out.println("Calculated Date is before the New date.");
    }
    Output:

    Calculated Date: Fri Jan 02 01:00:00 CET 1970
    New Date: Sat Aug 04 18:01:24 CEST 2007
    Calculated Date is before the New date.
    In the above example, we used two different constructors of Java Date class. We have two date to play with. Then we used method after() to check if the calculate date is after the new date or not.

  • before()

    Before() function is used to test if this date is before the specified date. It returns boolean value. Signature is: boolean before(Date when)

    Example:

    Java Code:
    Date midnight_jan2_1970 = new Date(24L*60L*60L*1000L);
    Date new_date = new Date();
    System.out.println("Calculated Date: " + midnight_jan2_1970);
    System.out.println("New Date: " + new_date);
    
    if (midnight_jan2_1970.before(new_date)) {
        System.out.println("Calculated Date is before the New date.");
    }
    Output:

    Calculated Date: Fri Jan 02 01:00:00 CET 1970
    New Date: Sat Aug 04 17:57:10 CEST 2007
    Calculated Date is before the New date.
    In the above example, we used two different constructors of Java Date class. We have two date to play with. Then we used method before() to check if the calculate date is before the new date or not.

  • clone()

    clone() function returns a copy of the object. Signature is: Object clone()

  • compareTo(Date)

    compareTo(Date) function is used to compare two dates. It takes another date object as argument and it returns integer. Signature is: int compareTo(Date anotherDate)

  • compateTo(Object)

    compareTo(Object) function is used to compare a date with another object. It takes another object as argument and it returns integer. Signature is: int compareTo(Object o)

  • equals(Object)

    equals(Object) is used to compare two dates for equality. Return value is boolean. Signature is: boolean equals(Object obj)

  • getDate()

    This method is deprecated and is replaced by Calendar.get(Calendar.DAY_OF_MONTH). Signature is: int getDate()

  • getDay()

    This method is deprecated and is replaced by Calendar.get(Calendar.DAY_OF_WEEK). Signature is: int getDay()

  • getHours()

    This method is deprecated and is replaced by Calendar.get(Calendar.HOUR_OF_DAY). Signature is: int getHours()

  • getMinutes()

    This method is deprecated and is replaced by Calendar.get(Calendar.MINUTE). Signature is: int getMinutes()
  • getSeconds()

    This method is deprecated and is replaced by Calendar.get(Calendar.SECOND). It returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
    Signature is: int getMinutes()

  • getMonth()

    This method is deprecated and is replaced by Calendar.get(Calendar.MONTH). Signature is: int getMonth()

  • getTimezoneOffset()

    This method is deprecated and is replaced by (Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000). Signature is: int getTimezoneOffset()

  • getYear()

    This method is deprecated and is replaced by Calendar.get(Calendar.YEAR) - 1900. Signature is: int getYear()

  • hashCode()

    hashCode() returns a hash code value for this object. Its return type is integer. Signature is: int hashCode()

  • parseString(String)

    ParseString() is deprecated and is replaced by DateFormat.parse(String s). It takes a String parameter and returns static long value. Signature is: static long parse(String s)

  • setDate(int)

    setDate(int) method is deprecated and is replaced by Calendar.set(Calendar.DAY_OF_MONTH, int date). It takes an integer parameter and returns void. Signature is: void setDate(int date)

  • setHours(int)

    setHours(int) is deprecated and is replaced by Calendar.set(Calendar.HOUR_OF_DAY, int hours). It takes integer parameter and returns void. Its signature is: void setHours(int hours)

  • setMinutes(int)

    setMinutes(int) is deprecated and is replaced by Calendar.set(Calendar.MINUTE, int minutes). It takes an integer parameter and returns void. Its signature is: void setMinutes(int minutes)

  • setMonth(int)

    setMonth(int) is deprecated and is replaced by Calendar.set(Calendar.MONTH, int month). It takes an integer parameter and returns void. Its signature is: void setMonth(int month)

  • setSeconds(int)

    setSeconds(int) is deprecated and is replaced by Calendar.set(Calendar.SECOND, int seconds). It takes an integer parameter and returns void. Its signature is: void setSeconds(int seconds)

  • setTime(long)

    setTime(long) is used to set the Date object. It takes a long parameter the time in milliseconds after January 1, 1970 00:00:00 GMT. It returns void. The signature is: void setSeconds(int seconds)

  • setYear(int)

    setYear(int) is deprecated and is replaced by Calendar.set(Calendar.YEAR, year + 1900). It takes an integer parameter and returns void. Its signature is: void setYear(int year)

  • toGMTString()

    toGMTString () is deprecated and is replaced by DateFormat.format(Date date), using a GMT TimeZone. It returns a String. Its signature is: String toGMTString()

  • toLocaleString()

    toLocalString () is deprecated and is replaced by DateFormat.format(Date date). It returns a String. Its signature is: String toLocalString()

  • toString()

    toString() is used to convert Date object into a String so we can use it as a String. It returns a String value. Its signarure is: String toString()

  • UTC(int, int, int, int, int, int)

    UTC(int, int, int, int, int, int) is deprecated and is replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec), using a UTC TimeZone, followed by Calendar.getTime().getTime(). It returns a static long value and takes 6 int values as input. Its signature is: static long UTC(int year, int month, int date, int hrs, int min, int sec)


Java Date Calculating Processing Time

Sometimes when programming, we need to know how much time a particular operation took. For example how much time a for loop took, how much time creating object of some class took and so on. This information can be very useful in optimizing the code. Java Date class can be used to get this useful information. Consider the following example:

Example:

Java Code:
Date d1 = new Date();
for(int i = 0; i<100;i++)
{
     System.out.print(".");
}

Date d2 = new Date();
long elapsed_time = d2.getTime() - d1.getTime();
System.out.println("Processing took " + elapsed_time + " milliseconds");
Output:

.................................................. ..................................................
Processing took 15 milliseconds
I created a Date object before the start of for loop using simple constructor, so object d1 gets current date and time. After for loop is done, I created another object of Date class called d1 which gets current date time. Difference between both dates gives me milliseconds that were consumed by the for loop.


Example:

Java Code:
Date now = new Date();
long nowLong = now.getTime();
System.out.println("Value is " + nowLong);
Output:

Value is 1186244714921
You might be amyzed that what kind of time is it. Actually its in milliseconds. I use the simple Date constructor to create a date. Then I used the getTime() method to find out the number of milliseconds that the date represents.


DateFormat Class

DateFormat class is a very useful class included in java.text package that can be used to display date in different formats. Following example will show you how to use it with Date object in meaningful way.

Example:

Java Code:
Date now = new Date();
DateFormat df =  DateFormat.getDateInstance();
DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM);
DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat df4 = DateFormat.getDateInstance(DateFormat.FULL); 
String s =  df.format(now);
String s1 = df1.format(now);
String s2 = df2.format(now);
String s3 = df3.format(now);
String s4 = df4.format(now);
System.out.println("(Default) Today is " + s);
System.out.println("(SHORT)   Today is " + s1);
System.out.println("(MEDIUM)  Today is " + s2);
System.out.println("(LONG)    Today is " + s3);
System.out.println("(FULL)    Today is " + s4);
Output:

(Default) Today is 04.08.2007
(SHORT) Today is 04.08.07
(MEDIUM) Today is 04.08.2007
(LONG) Today is 4. August 2007
(FULL) Today is Samstag, 4. August 2007