October 29, 2025
Date and Time in Java

Java – Date and Time – Part 1

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.

 

SNMethods  and Description
1boolean 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.

2boolean 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.

3Object clone( )

Duplicates the invoking Date object.

4int 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.

5int compareTo(Object obj)

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

6boolean 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.

7long getTime( )

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

8int hashCode( )

This returns a hash code equivalent for an object.

9void 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.

10String 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 CodeBrief descriptionE.g
GEra designatorAD
yYear in four digits2017
MMonth of yearJuly or 07
dDay of month11
hHour in A.M./P.M. (1~12)12
HHour in 24 hour format21
mMinute in hour56
sSecond in minute45
SMillisecond326
EDay of weekWednesday
DDay of year240
FDay of week in month2 (second Mon. in May)
wWeek in year30
WWeek in month3
aA.M./P.M. markerPM
kHour in 24 hour format24
KHour in A.M./P.M. (0~11)10
zTime zoneEastern Standard Time
Escape for textDelimiter
Single quote`

Listing 1.1: Table of SimpleDateFormat Codes

 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x