How to Get Date and Time in Java – Java Date Class

Date and Time play a very important role in our life and are important factors used in every technology in this world. It is considered a very important and critical factor in the transaction systems where a single millisecond can cause a change in the system.

For example, take a scenario of Railway reservation system; If a user books a ticket for a seat in a train and at the same time another user tries to book the same seat. But the time when the first user requested was stored in the database and restricts any other user to book the same seat. Here is the major role of Date and Time.

In this article, we will study how the Java programming language facilitates us with the functionality of Date and Time. Java provides Date class along with the methods to format the Date and Time and also to get the current date and time. Let’s start discussing Date and Time in Java.

Date and Time in java

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Date and Time in Java- The Date class

Java comes with the Date class that is located in the java.util package and provides many methods to perform operations with date and time. The Date class of Java implements the Cloneable, Serializable, and Comparable interfaces of Java.

Constructors of the Date class

There are also six java constructors of the Date class but four of them are deprecated and therefore only two of them are used. These two constructors are listed below with the description:

1. Date()

This is the non-parameterized constructor of the Date class and is used to initialize the Date class object with the current date and time.

2. Date(long millisec)

It is a parameterized constructor of the Date class and we pass one argument to it in the form of milliseconds. This constructor creates for us an object of the Date class for the given input milliseconds since midnight, January 1, 1970

Methods of Java Date class

S.N. Method Description
1 boolean after(Date date) This method returns true if the current object of the Date class contains the date which is later than the date specified in the parameter of the method, otherwise, it returns false.
2 boolean before(Date date) This method returns true if the current object of the Date class contains the date which is earlier than the date specified in the parameter of the method, otherwise, it returns false.
3 Object clone( ) This method creates a duplicate copy of the invoking Date class object.
4 int compareTo(Date date) This method is used to compare the value of the invoking object with the specified date. It returns 0 if the values are equal, a negative value if the invoking object is earlier than the date and a positive value if the invoking object is later than date.
5 int compareTo(Object obj) This method works identical to the compareTo(Date) method if the object is of Date type. If it is not, then the method throws the ClassCastException.
6 boolean equals(Object date) This method returns true if the invoking object of the Date class contains the same time and date as the one specified by date, otherwise, it returns false.
7 long getTime( ) This method returns the number of milliseconds that have elapsed since January 1, 1970.
8 int hashCode( ) This method gives the hash code value for the invoking Date object.
9 void setTime(long time) This method is used to set the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970.
10 String toString( ) Returns the String representation of the invoking Date class object.

Getting Current Date and time of the system

We can easily retrieve the current date and time of our system using two ways:

  1. Using the Date class
  2. Using the Calendar class

1. Using Date class in Java

This is the easiest method to get the current date and time of the system. We can create the object of the Date class and call the toString() method from this object to get the current date and time.

Code to get the current date and time using the Date class:

package com.techvidvan.dateandtime;
import java.util.Date;
public class DateDemo {
  public static void main(String args[]) {
    // Instantiating a Date object
    Date date = new Date();

    // display time and date using toString() method
    System.out.println("The current date and time is: ");
    System.out.println(date.toString());
  }
}

Output:
The current date and time is:
Tue Apr 07 03:20:26 IST 2020

2. Using Calendar class

We can also use the Calendar class to get the current date and time.We create the instance of the Calendar class using the getInstance() method and then call the getTime() method to get the current date and time.

Code to get the current date and time using the Calendar class:

package com.techvidvan.dateandtime;
import java.util.Date;
import java.util.Calendar;
public class CalendarDemo {
  public static void main(String args[]) {
    // Instantiating a Calendar object
    Calendar c = Calendar.getInstance();
    // displaying the  time and date using getTime()
    System.out.println("The current date and time is: ");
    System.out.println(c.getTime());
  }
}

Output:
The current date and time is:
Tue Apr 07 03:29:04 IST 2020

Date Formatting Using SimpleDateFormat class

We can also get the Date and time in the desired format by using the SimpledateFormat class which is a concrete class that allows us to format and parse the date and time in the desired manner. This class is located in the java.text package.

Code to format the date and time using the SimpleDateFormat class:

package com.techvidvan.dateandtime;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class GettingCurrentDate {
  public static void main(String[] args) {
    //getting current date and time using Date class
    System.out.println("Using Date class:");
    System.out.println("The formatted date and time is:");
    DateFormat df = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
    Date dateobj = new Date();
    System.out.println(df.format(dateobj));

    //getting current date time using calendar class 
    System.out.println("\nUsing Calendar class:");
    System.out.println("The formatted date and time is:");
    Calendar calobj = Calendar.getInstance();
    System.out.println(df.format(calobj.getTime()));
  }
}

Output:
Using Date class:
The formatted date and time is:
07/04/20 04:10:28

Using Calendar class:
The formatted date and time is:
07/04/20 04:10:28

So, this is how we can get the formatted date and time.

SimpleDateFormat Format Codes

We can also use some codes to specify the time format using a time pattern string. There are some ASCII letters that are reserved as pattern letters, which are listed in the below table with examples:

Character Description Example
G Era designator AD or BC
y Year in four digits 2019
M Month in year March or 03
d Day in month 25
h Hour in A.M./P.M. (1~12) 8
H Hour in day (0~23) 20
m Minute in hour 48
s Second in minute 59
S Millisecond 238
E Day in week Friday
D Day in year 250
F Day of week in month 2 (second Wed. in July)
w Week in year 25
W Week in month 3
a A.M./P.M. marker PM
k Hour in day (1~24) 24
K Hour in A.M./P.M. (0~11) 10
z Time zone Indian Standard Time
Escape for text Delimiter
Single quote `

 

Let’s see an example where we have used some of the codes in the program:

package com.techvidvan.dateandtime;
import java.util. * ;
import java.text. * ;
public class FormatCodesDemo {
  public static void main(String args[]) {
    Date date = new Date();
    SimpleDateFormat formatObj = new SimpleDateFormat("E W yyyy.MM.dd 'at' hh:mm:ss a zzz");
    System.out.println("Current Date: " + formatObj.format(date));
  }
}

Output:
Current Date: Tue 2 2020.04.07 at 05:04:48 PM IST

Java Date and Time Conversion Characters

Character Description Example
c Complete date and time Wed April 08 09:06:54 IST 2020
F ISO 8601 date 2020-08-09
D U.S. formatted date (month/day/year) 12/29/2014
T 24-hour time 17:05:18
r 12-hour time 03:45:19 pm
R 24-hour time, no seconds 18:54
Y Four-digit year (with leading zeroes) 2019
y Last two digits of the year (with leading zeroes) 19
C First two digits of the year (with leading zeroes) 20
B Full month name June
b Abbreviated month name Mar
m Two-digit month (with leading zeroes) 02
d Two-digit day (with leading zeroes) 03
e Two-digit day (without leading zeros) 8
A Full weekday name Saturday
a Abbreviated weekday name Sat
j Three-digit day of year (with leading zeroes) 068
H Two-digit hour (with leading zeroes), between 00 and 23 20
k Two-digit hour (without leading zeros), between 0 and 23 18
I Two-digit hour (with leading zeros), between 01 and 12 06
l Two-digit hour (without leading zeros), between 1 and 12 6
M Two-digit minutes (with leading zeroes) 05
S Two-digit seconds (with leading zeroes) 19
L Three-digit milliseconds (with leading zeroes) 047
N Nine-digit nanoseconds (with leading zeroes) 047000000
P Uppercase morning or afternoon marker PM
p Lowercase morning or afternoon marker pm
z RFC 822 numeric offset from GMT -0800
Z Time zone IST
s Seconds since 1970-01-01 00:00:00 GMT 1078884319
Q Milliseconds since 1970-01-01 00:00:00 GMT 1078884319047

Date Formatting Using printf

We can also format the date using the printf method. We have to use a two-letter format, starting with t and ending in any one of the letters of the above table.

Let’s understand this concept with a program:

Code to format the date using the printf method:

package com.techvidvan.dateandtime;
import java.util.Date;
public class DateDemo {
  public static void main(String args[]) {
    // Instantiating a Date object
    Date date = new Date();

    // displaying time and date
    String string = String.format("Current Date/Time is: %tc", date);
    //Using the printf method
    System.out.printf(string);
  }
}

Output:
Current Date/Time is: Tue Apr 07 05:20:59 IST 2020

You can also use the <flag alternatively. This is shown in below example:

package com.techvidvan.dateandtime;
import java.util.Date;
public class DateDemo {
  public static void main(String args[]) {
    // Instantiate a Date object
    Date date = new Date();

    // display formatted date
    System.out.printf("%s %tB %<te, %<tY", "Today's date:", date);
    System.out.printf("%s %tr ", "\nCurrent time:", date);
    System.out.printf("%s %tZ ", "\nCurrent Zone:", date);
  }
}

Output:
Today’s date: April 7, 2020
Current time: 05:35:47 PM
Current Zone: IST

Parsing Strings into Dates

There are also some additional methods in SimpleDateFormat; one of them is the parse() method that is used to parse a string according to the format stored in the given SimpleDateFormat object.

Code to parse the String into date:

package com.techvidvan.dateandtime;
import java.util. * ;
import java.text. * ;

public class DateDemo {
  public static void main(String args[]) {
    SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
    String input = "2020-07-04";

    System.out.println("Input string is: " + input);

    Date date;
    try {
      date = ft.parse(input);
      System.out.println("Parsed string is :");
      System.out.println(date);
    }
    catch(ParseException e) {
      System.out.println("Unparseable string");
    }
  }
}

Output:
Input string is: 2020-07-04
Parsed string is :
Sat Jul 04 00:00:00 IST 2020

Sleeping for a While

We can also use the sleep() method of Thread class to sleep for any duration of time starting from one ms to the lifetime of your computer. For example, in the below code the program will sleep for 5 seconds:

Code to sleep for a while:

package com.techvidvan.dateandtime;
import java.util. * ;
public class SleepDemo {
  public static void main(String args[]) {
    try {
      System.out.println("Before sleeping:");
      System.out.println(new Date());
      //sleeping for 5 seconds 
      Thread.sleep(5000);
      System.out.println("After sleeping for 5 seconds:");
      System.out.println(new Date());
    }
    catch(Exception e) {
      System.out.println("Failed!");
    }
  }
}

Output:
Before sleeping:
Tue Apr 07 05:07:23 IST 2020
After sleeping for 5 seconds:
Tue Apr 07 12:07:28 IST 2020

GregorianCalendar Class

The GregorianCalendar is a concrete implementation of the Calendar class that we studied in the previous section of this article. The GregorianCalendar class is initialized with the current date and time with the help of getInstance() method of the Calendar class. It  defines two fields: AD(After Death) and BC(Before Christ). These two fields represent the two eras defined by the real-life Gregorian calendar.

There are some constructors of the GregorianCalendar class which are−

S.N. Constructor  Description
1 GregorianCalendar() Constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
2 GregorianCalendar(int year, int month, int date) Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
3 GregorianCalendar(int year, int month, int date, int hour, int minute) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
4 GregorianCalendar(int year, int month, int date, int hour, int minute, int second) Constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
5 GregorianCalendar(Locale aLocale) Constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
6 GregorianCalendar(TimeZone zone) Constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
7 GregorianCalendar(TimeZone zone, Locale aLocale) Constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

GregorianCalendar Support Methods

S.N. Method  Description
1 void add(int field, int amount) Adds the specified (signed) amount of time to the given time field, based on the calendar’s rules.
2 protected void computeFields() Converts UTC as milliseconds to time field values.
3 protected void computeTime() Overrides Calendar Converts time field values to UTC as milliseconds.
4 boolean equals(Object obj) Compare this GregorianCalendar to an object reference.
5 int get(int field) Gets the value for a given time field.
6 int getActualMaximum(int field) Returns the maximum value that this field could have, given the current date.
7 int getActualMinimum(int field) Returns the minimum value that this field could have, given the current date.
8 int getGreatestMinimum(int field) Returns the highest minimum value for the given field if it varies.
9 Date getGregorianChange() Gets the Gregorian Calendar change date.
10 int getLeastMaximum(int field) Returns the lowest maximum value for the given field if it varies.
11 int getMaximum(int field) Returns maximum value for the given field.
12 Date getTime() Gets this Calendar’s current time.
13 long getTimeInMillis() Get this Calendar’s current time as a long.
14 TimeZone getTimeZone() Gets the time zone.
15 int getMinimum(int field) Returns minimum value for the given field.
16 int hashCode() Overrides hashCode.
17 boolean isLeapYear(int year) Determines if the given year is a leap year.
18 void roll(int field, boolean up) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
19 void set(int field, int value) Sets the time field with the given value.
20 void set(int year, int month, int date) Sets the values for the fields year, month, and date.
21 void set(int year, int month, int date, int hour, int minute) Sets the values for the fields year, month, date, hour, and minute.
22 void set(int year, int month, int date, int hour, int minute, int second) Sets the values for the fields year, month, date, hour, minute, and second.
23 void setGregorianChange(Date date) Sets the GregorianCalendar change date.
24 void setTime(Date date) Sets this Calendar’s current time with the given Date.
25 void setTimeInMillis(long millis) Sets this Calendar’s current time from the given long value.
26 void setTimeZone(TimeZone value) Sets the time zone with the given time zone value.
27 String toString() Returns a string representation of this calendar.

Code to understand the Gregorgian Calendar:

package com.techvidvan.dateandtime;
import java.util. * ;
public class GregorianCalendar Demo {
  public static void main(String args[]) {
    String months[] = {
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec"
    };

    int year;

    GregorianCalendar gCalendar = new GregorianCalendar();

    //Display the current time and date information.
    System.out.print("Today is: ");
    System.out.print(months[gCalendar.get(Calendar.MONTH)]);
    System.out.print(" " + gCalendar.get(Calendar.DATE) + " ");
    System.out.println(year = gCalendar.get(Calendar.YEAR));
    System.out.print("Current time: ");
    System.out.print(gCalendar.get(Calendar.HOUR) + ":");
    System.out.print(gCalendar.get(Calendar.MINUTE) + ":");
    System.out.println(gCalendar.get(Calendar.SECOND));

    // Test if the current year is a leap year
    if (gCalendar.isLeapYear(year)) {
      System.out.println("The current year is a leap year");
    }
    else {
      System.out.println("The current year is not a leap year");
    }
  }
}

Output:
Today is: Apr 7 2020
Time: 18:6:45
The current year is a leap year

Conclusion

Here we come to the end of the article on Date and Time in Java. The Date class of java.util package plays a very important role in performing operations with date and time. We can use the SimpleFormatClass and its codes to format the date in the desired manner. We can also sleep the system for some seconds using the sleep method of Thread class.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.