Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

java.util.Date Example – How to use Date

In this example we will show how to use java.util.Date class. Class Date represents a specific instant in time, with millisecond precision.

1. Date constructors

The java.util.Date class supports two constructors:

  • Date()

This constructor initializes a Date object with the current date and time. Time is measured to the nearest millisecond.

  • Date(long millisec)

This constructor initializes a Date object so as to represent the specified number of milliseconds since the January 1, 1970, 00:00:00 GMT. ( This time is the standard base time known as “the epoch”).

2. Date methods

Here are the methods provided by the class Date. After creating a Date object, you can call any of the below methods by using this object.

  • boolean after(Date when)
    Checks if the invoking Date object is later than the specified date.
  • boolean before(Date when)
    Checks if the invoking Date object is earlier than the specified date.
  • Object clone()
    Returns a copy of the invoking Date object.
  • int compareTo(Date date)
    Compares the invoking Date object with the specified date and returns 0 if the two values are equal, negative value if the invoking object is earlier than the specified date and positive value if the invoking object is later than the specified date.
  • boolean equals(Object date)
    Check if the invoking Date object and the specified date are equal.
  • long getTime()
    Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by the invoking Date object.
  • int hashCode()
    Returns a hash code value for the invoking Date object.
  • void setTime(long time)
    Sets the invoking Date object to represent the specified time, which is the time in milliseconds after January 1, 1970 00:00:00 GMT.
  • String toString()
    Converts the invoking Date object to a String.

For further details for each of the above methods you can have a look at class Date JavaDoc.

3. Examples of using Date class

Create a java class named DateExample.java with the following code:

DateExample.java

import java.util.*;
import java.text.*;

public class DateExample {
	public static void main(String args[]) {

		// Instantiate a Date object
		Date date = new Date();

		// Get current date and time
		
		// 1st way: current time and date using toString()
		System.out.println("Today's date is: "+date.toString());

		// 2nd way: current time and date using SimpleDateFormat
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
		System.out.println("Today's date is: "+dateFormat.format(date));

		// Convert string to date
		SimpleDateFormat dateformat2 = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
		String strdate2 = "02-04-2013 11:35:42";
		try {
			Date newdate = dateformat2.parse(strdate2);
			System.out.println(newdate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		

		// Date Comparison
	
		// 1st way: using before(), after(), equals()
		SimpleDateFormat dateformat3 = new SimpleDateFormat("dd/MM/yyyy");
		try {
			Date date1 = dateformat3.parse("17/07/1989");
			Date date2 = dateformat3.parse("15/10/2007");
			
			System.out.println("Date1 is: "+dateformat3.format(date1));
			System.out.println("Date2 is: "+dateformat3.format(date2));

			if (date1.after(date2)) {
				System.out.println("Date1 is later than Date2");
			}else if (date1.before(date2)) {
				System.out.println("Date1 is earlier than Date2");
			}else if (date1.equals(date2)) {
				System.out.println("Date1 is the same with Date2");
			}

			// 2nd way: using compareTo()
			date1 = dateformat3.parse("27/09/2012");
			date2 = dateformat3.parse("27/09/2009");

			System.out.println("Date1 is: "+dateformat3.format(date1));
			System.out.println("Date2 is: "+dateformat3.format(date2));

			if (date1.compareTo(date2) > 0) {
				System.out.println("Date1 is later than Date2");
			} else if (date1.compareTo(date2) < 0) {
				System.out.println("Date1 is earlier than Date2");
			} else if (date1.compareTo(date2) == 0) {
				System.out.println("Date1 is the same with Date2");
			}

		} catch (ParseException e) {
			e.printStackTrace();
		}

	}
}

We can see in the above code that there is an extended use of class java.text.SimpleDataFormat. This class is very useful as it provides many patterns for formatting and parsing dates.Let's give a short explanation of our code:
Firstly, we show two ways for getting current date and time. The first way is to use method toString() and the second way is to use the class java.text.SimpleDataFormat and the method format(), which converts the given date to string.
Then, we can see how to convert a string to date, by using the method parse(). Note that the given date must be of the same pattern with the invoking java.text.SimpleDataFormat object.
Finally, we demonstrate two ways for comparing two dates, either by using the methods before(), after(), equal() or by using the method compareTo().
If we run the above code, we will have the following results:

  • Output:
Today's date is: Thu Jan 02 16:00:56 EET 2014
Today's date is: 02/01/2014 04:00:56
Tue Apr 02 11:35:42 EEST 2013
Date1 is: 17/07/1989
Date2 is: 15/10/2007
Date1 is earlier than Date2
Date1 is: 27/09/2012
Date2 is: 27/09/2009
Date1 is later than Date2

4. Download the source code

This was an example of using class Date. Download the source code here: DateExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close