Java Date Class

The java.util.Date class represents a specific instant in time, with millisecond precision. This class extend Object class and implements Serializable, Cloneable and Comparable interfaces. It provides constructors and methods to deal with date and time with Java.

 

Class constructors

The following list describes the constructors of Java Date class:

Table 1. Constructors of java.util.Date class

Sl. No.

Constructor and Description

1

Date()

This constructor allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

2

Date (long date)

This constructor allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as “the epoch”, namely January 1, 1970, 00:00:00 GMT.

 

Class Methods

Below is a list describing several methods that Java Date class offers:

Table 2. Methods in java.util.Date

Sl. No.

Method and Description

1

boolean after (Date when)

This method tests if this date is after the specified date.

2

boolean before (Date when)

This method tests if this date is before the specified date.

3

Object clone()

This method return a copy of this object.

4

int compareTo (Date anotherDate)

This method compares two Dates for ordering.

5

boolean equals (Object obj)

This method compares two dates for equality.

6

long getTime()

This method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

7

int hashCode()

This method returns a hash code value for this object.

8

void setTime (long time)

This method sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.

9

String toString()

This method converts this Date object to a String of the form.

 

SimpleDateFormat class

Java provides a class called a SimpleDateFormat that allows us to format and parse dates as per our requirements.

The following table lists basics of the date format with regard to this class.

LetterDate or Time ComponentExamples
GEra designatorAD
yYear2019
MMonth in yearJuly or Jul or 19
wWeek in year27
WWeek in month2
DDay in year189
dDay in month10
FDay of week in month2
EDay name in weekMonday or Mon
uDay number of week (1 = Monday, …, 7 = Sunday)1
aAM/PM markerPM
HHour in day (0-23)0
kHour in day (1-24)24
KHour in am/pm (0-11)0
hHour in am/pm (1-12)12
mMinute in hour30
sSecond in minute55
SMillisecond978
zTime zonePacific Standard Time; PST; GMT-08:00
ZTime zone-0800
XTime zone-08 or -0800 or -08:00

 

Date Class Example

The following program demonstrates the important methods of Date class.

DateClassDemo.java

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

public class DateClassDemo {

public static void main(String[] args) {
// Constructor 1
Date date = new Date(); //creating object
System.out.println("Date constructor example:~");
System.out.println("Current date is: " + date);

// Date format is Specified
String dateFormat = "hh:mm:ss a dd-MMM-yyyy";
// Date format string is passed as an argument to the Date format object
SimpleDateFormat obj = new SimpleDateFormat(dateFormat);
//Date formatting is applied to the current date
System.out.println("Formatted current date is: " +obj.format(date));

// Constructor 2
date = new Date(173924667L); //creating object
System.out.println("Date provided here is: " + date);

// Formatting dates using "dd-mm-yyyy" format
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy");
System.out.println("\nDate comparison example:~");
Date date1 = null, date2 = null;
try {
date1 = sdf.parse("15-01-2020");
date2 = sdf.parse("10-01-2020");
}
catch (ParseException ex) {
System.out.println(ex);
}
System.out.println("Date1 : " + sdf.format(date1));
System.out.println("Date2 : " + sdf.format(date2));

// Comparison of dates using compareTo(), after() and before() methods
System.out.println("Comparison1: " + date1.compareTo(date2)); //1
System.out.println("Comparison2: " + date1.after(date2)); //true
System.out.println("Comparison3: " + date1.before(date2)); //false
}
}

Output:

Date constructor example:~
Current date is: Wed Jan 15 15:59:37 IST 2020
Formatted current date is: 03:59:37 PM 15-Jan-2020
Date provided here is: Sat Jan 03 05:48:44 IST 1970

Date comparison example:~
Date1 : 15-01-2020
Date2 : 10-01-2020
Comparison1: 1
Comparison2: true
Comparison3: false

 

Calendar and LocalDate classes

Now-a-days, Date class is rarely used Java; instead, the developers mainly use Calendar and LocalDate classes. Similarly, for time we have LocalTime class.

To get parts of a date (year, month, day of month) :—

The methods to get the year, month, day of month, hour etc. are deprecated. If we need to get or set the year, month, day of month etc. better use a java.util.Calendar instead.

java.util.Calendar calendar = new java.util.GregorianCalendar();

int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); // Jan = 0, not 1
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);

int hour = calendar.get(Calendar.HOUR); // 12 hour clock
int hourOfDay = calendar.get(Calendar.HOUR_OF_DAY); // 24 hour clock
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int millisecond = calendar.get(Calendar.MILLISECOND);

NOTE: The above example can also be replaced by LocalDate class.

 

Calendar and LocalDate Example

See the following example below.

NewDateExample.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Calendar;
import java.util.Date;

public class NewDateExample {

public static void main(String[] args) {
Date date = null;
// To know current date using Java SE 8 style
LocalDate today = LocalDate.now();
System.out.println("Today's local date : " + today);

// To get date parts (year, month, day of month)
int day = today.getDayOfMonth();
int month = today.getMonthValue();
int year = today.getYear();
System.out.println("Today's date is : " + day + "/" + month + "/" + year);

// To know current time using Java SE 8 style
LocalTime time = LocalTime.now();
System.out.println("Local time now : " + time);

// Convert Date to Calendar
SimpleDateFormat sdf = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
try {
date = sdf.parse("15-01-2020 03:42:36");
} catch (ParseException ex) {
System.out.println(ex);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("Given date (from Date to Calendar): " + date);

// Convert Calendar to Date
calendar = Calendar.getInstance();
date = calendar.getTime();
System.out.println("Given date (from Calendar to Date): " + date);
}
}

Output:

Today's local date : 2020-01-15
Today's date is : 15/1/2020
Local time now : 16:22:38.691
Given date (from Date to Calendar): Wed Jan 15 03:42:36 IST 2020
Given date (from Calendar to Date): Wed Jan 15 16:22:38 IST 2020