Java Date and Time With Examples

In our previous lessons, we discussed the classes which are part of java.lang. java.lang is a package (We will discuss package in our upcoming topics) which is implicitly imported to every java program. As a result, it was never seen in our examples but was always there.

We are going to discuss how can we store, process, and manipulate the date and time information. Java has a package called java.util which contains various utility as Scanner, Arrays, ArrayList, Set, etc. There also exists a Date class which will be discussed in this lecture.

As the name indicates, it serves the purpose of storage and processing of date and time.

Creating a Date Object

The Date class has two versions of constructor which is used to create an instance. As said in our previous lectures, using a new keyword calls the constructor and creates an object.

Date(): 

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date(); //myDate object is created and initialized with the current date and time.
        System.out.println(myDate.toString());
     }
}

Output:

Thu Sep 24 11:57:20 UTC 2020

Date(long x) :                                                                                                 

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date(644365);//myDate object is created and initialized with the date and time equivalent to x milliseconds passed since January 1st, 1970 00:00 hrs.
        System.out.println(myDate.toString());
     }
}

Output:

Thu Jan 01 00:10:44 UTC 1970

Methods of class Date

This Date class provides a range of methods, that allows comparison between two dates, getting and setting time, parsing the time to string. Let us look into them.

Java.util.Date.after() Method:

Name: after(Date inputDate)
Return: boolean
Description: It returns true only if the calling Date object contains a date that is earlier than the input Date, else it returns false.

Example:

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date();
        Date myDate2 = new Date(7575668);
        
        System.out.println(myDate.after(myDate2));
     }
}

Output:

true

Java.util.Date.before() Method:

Name: before(Date inputDate)
Return: boolean
Description: It returns true only if the calling Date object contains a date that is later than the input Date, else it returns false.

Example:

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date();
        Date myDate2 = new Date(7575668);
        
        System.out.println(myDate.before(myDate2));
     }
}

Output:

false

Java.util.Date.equals() Method:

Name: equals(Object inputDate)
Return: boolean
Description: It returns true only if the calling Date object contains a date and time the same as the input Date, else it returns false.

Example:

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date();
        Date myDate2 = new Date(7575668);
        
        System.out.println(myDate.equals(myDate2));  //Two different date
        System.out.println(myDate.equals(myDate));  //Same dates
     }
}

Output:

false
true

Java.util.Date.compareTo() Method:

Name: compareTo(Date inputDate)
Return: int
Description: It returns 0  if the calling Date object is equal to the input Date. It returns a negative value if the calling  Date is earlier than inputDate and a positive value if the calling  Date is later than inputDate.

Example:

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date();
        Date myDate2 = new Date(7575668);
        
        System.out.println(myDate.compareTo(myDate2));  //Two different date
        System.out.println(myDate.compareTo(myDate));  //Same dates
     }
}

Output:

1
0

Java.util.Date.getTime() Method:

Name: getTime()
Return: long
Description: It returns the milliseconds that have passed since January 1st, 1970 00:00 hrs.

Example:

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date();
        Date myDate2 = new Date(7575668);
        
        System.out.println(myDate.getTime());  
        System.out.println(myDate2.getTime());  
     }
}

Output:

1600949545956
7575668

Java.util.Date.setTime() Method:

Name: setTime(long x)
Return: void
Description: It sets the date and time equivalent to x milliseconds passed since January 1st, 1970 00:00 hrs.

Example:

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date();
        System.out.println("Before: "+myDate.getTime());  
        myDate.setTime(7575668);
        System.out.println("After: "+myDate.getTime()); 
     }
}

Output:

Before: 1600949668930
After: 7575668

Java.util.Date.toString() Method:

Name: toString()
Return: String
Description: It converts the calling Date object into String and returns it

Example:

import java.util.*;
public class MyDateTime{

     public static void main(String []args){
        Date myDate = new Date(); //myDate object is created and initialized with the current date and time.
        System.out.println(myDate.toString());
     }
}

Output:

Thu Sep 24 12:16:38 UTC 2020

Formatting Dates

We can see that toString() converts the Date into String which is the default. Java gives the feature of formatting our Date object as per requirement. The table mentioned below gives the pattern letters which have their significance in terms of formatting.

Pattern Letter Significance Example
S Milliseconds 346
S Second in a minute 25
M Minute in a hour 46
H 12 hr Pattern in AM/PM 8
H 24 hr Pattern 21
D Day in a month 25
D Day in a year 256
E Day in a week Wednesday
W Week in a year 52
W Week in a month 2
Z Time zone EST/IST
M Month in Year May/5
Y Year in four digits 1987

There is another class SimpleDateFormat(a member of java.text package) which is dedicated to the formatting and parsing of dates using user-defined formats are mentioned above. The instance of SimpleDateFormat creates a format, and upon passing the date in format() return the Date mentioned in a specified format.

We are presenting a series of examples that showcase the utility of pattern letters and SimpleDateFormat.

Example 1: Using printf(), SimpleDateFormat, and pattern letters

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

public class myDateTime{
	public static void main(String args[]) {
		Date myDate = new Date();
		SimpleDateFormat myFormat =new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
		System.out.println("Current Date(Default): " + myDate.toString());
		System.out.println("Current Date: " + myFormat.format(myDate));
	}
}

Output:

Current Date(Default): Thu Sep 24 12:26:33 UTC 2020
Current Date: Thu 2020.09.24 at 12:26:33 PM UTC

Example 2: Using only printf() and pattern letters

Date and time formatting can be done very easily using printf() method. You use a two-letter format, starting with t and ending with pattern letters.

import java.util.Date;

public class MyDateTime {
	public static void main(String args[]) {
		Date date = new Date(); 
		String str = String.format("Formatted Current Date & Time : %tc", date );
		System.out.printf(str);
	}
}

Output:

Formatted Current Date & Time : Thu Sep 24 12:35:28 UTC 2020

Example 3:

In order to avoid formatting each part separately, the format string can identify the index of the parameter to be formatted. The index starts with % and ends at $.  One should notice <, which indicates that the same parameter is to be used as in the preceding format specification

import java.util.Date;

public class MyDateTime {
	public static void main(String args[]) {
		Date myDate = new Date();
		System.out.printf("%1$s %2$tB %2$td, %2$tY\n", "Formatted date using % $:", myDate);
		System.out.printf("%s %tB %<te, %<tY", "Formatted date using % <:", myDate);
	}
}

Output:

Formatted date using % $: September 24, 2020
Formatted date using % <: September 24, 2020

Java has a series of Classes that deal with various conversions, parsing, formatting of dates, and time. It is expected from our readers to explore more. We will be discussing Java Arrays.