Java – Date and Time – Part 1

Date and Time in Java

In this lesson, you will learn how to use date and time data in Java. The Date class is found in the java.util package. However this class covers both date and time values. So there is no separate time class.

 

We would cover the following

  1. Date Constructor
  2. Methods of the Date Class
  3. Getting Current Date and Time
  4. Comparing Dates
  5. Formatting Dates using SimpleDateFormat
  6. SimpleDateFormat Codes

 

1. Date Constructor

The Date class provides both constructors and methods. You use the constructors to create new dates. Similarly, you use the methods to manipulated date data.

I have provided the two constructors below. Also, description of each is provided as well.

 

Date (): You use this constructor to create a date object with the current date and time

Date (long milisec): You use this constructor to create new date as well. But this constructor accepts an argument. The argument is the number of miliseconds that have elapsed since 1, January 1970 midnight.

 

 

2. Methods of the Date Class

We have various useful methods in the date class.

 

SN Methods  and Description
1 boolean after(Date date)

Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.

2 boolean before(Date date)

Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.

3 Object clone( )

Duplicates the invoking Date object.

4 int compareTo(Date date)

This method compares the value of an object with that of date. It returns 0 if the values are equal. But a negative value if the object is earlier than the date. And a positive value is returned if the object is later than date.

5 int compareTo(Object obj)

This is similar to compareTo(Date) if obj is of class Date. If not, it throws a ClassCastException.

6 boolean equals(Object date)

This method returns true if the a Date object contains the same time and date as the one specified by date parameter. If not, it returns false.

7 long getTime( )

This method returns the number of milliseconds that have passed since 1st January 1970.

8 int hashCode( )

This returns a hash code equivalent for an object.

9 void setTime(long time)

You uses this to set the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, 1st January 1970.

10 String toString( )

This method converts a Date object into a string and returns the result. You probably will use it more often

Listing 1.0: Methods of the Date Class

 

 

3. Getting Current Date and Time

You would oftentimes need to use the current date and time. So how do you get it? Very easy. You get it by just calling the toString method of a Date object. These are the steps:

  • First you create a date object
  • Second, you call the toString method

You can however do these two operations in a single line. Look at the code below

 

import java.util.Date;

public class DateDemo {

	public static void main(String[] args) {
		
		//Create a new date
		Date date = new Date();
		
		//Display the value
		System.out.println(date.toString());		
	}
}

Listing 1.0: Getting the current Date

 

Notice from  the code in Listing 1.0 that we import java.util.date. So the Date class is inside the java.util package. If you run the code above, then you will have the output below.

 

Sat Jan 19 11:53:41 CET 2019

 

4. Comparing Dates

You probably will need to compare two date to see if they are equal. Or maybe to see if one date precede the other. There are three ways to do this

First Method: You can use the compareTo () method. This method is defined in the Comparable interface. It is however implemented by the Date class

Second Method: You can use the getTime() method. This method gives you the number of miliseconds that have elapsed since 1st January, 1970. Get this value for both dates and then check if the two values are the same

Third Method: You can use the methods before(), after() and equals(). This method are provided in the Date class.

 

5. Formatting Date Using SimpleDateFormat

The SimpleDateFormat() allows you to format date in different formats.  So you specify a pattern that you want the date to be formatted in. However, you first need to create SimpleDateFormat object.

For example, the code in Listing 1.1 displays a date formatted using SimpleDateFormat.

 

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDemo {

	public static void main(String[] args) {
			
			//Create a new date
			Date date = new Date();
			
			//Create a SimpleDateFormat
			SimpleDateFormat ft = 
			new SimpleDateFormat("E yyyy-MMM-dd 'at' hh:mm:ss a zzz");
			
			//Print the date
			System.out.println("Today's date: " + ft.format(date));					
	}
}

Listing 1.1: Printing current date using SimpleDateFormate

 

I recommend you try to run this code yourself. If you do, you will have the output shown below. Also try to change things a bit and see what output you get. Next section explains the codes!

Today's date: Sat 2019-Jan-19 at 12:12:04 PM CET

 

6. SimpleDateFormate Codes

You can find the the meaning of the codes in Table 1.1. I suggest you takes some time to go through. So you get your head around them. You also kind of gradually get used to them.

 

Character Code Brief description E.g
G Era designator AD
y Year in four digits 2017
M Month of year July or 07
d Day of month 11
h Hour in A.M./P.M. (1~12) 12
H Hour in 24 hour format 21
m Minute in hour 56
s Second in minute 45
S Millisecond 326
E Day of week Wednesday
D Day of year 240
F Day of week in month 2 (second Mon. in May)
w Week in year 30
W Week in month 3
a A.M./P.M. marker PM
k Hour in 24 hour format 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Eastern Standard Time
Escape for text Delimiter
Single quote `

Listing 1.1: Table of SimpleDateFormat Codes