Table of contents
1.
Introduction
2.
What is a Date Class in Java?
3.
Constructors
3.1.
Code
3.2.
Output
4.
Methods
4.1.
 Code
4.2.
Output
5.
Display Current Date and Time
5.1.
Code
5.2.
Output
6.
Formatting Date and Time
6.1.
Code
6.2.
Output
7.
Frequently Asked Questions
7.1.
What is the default pattern for dates printed in java?
7.2.
Which class can be used to convert a date to a specific instant in time and a set of calendar fields?
7.3.
What can be used to print time in nanoseconds?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Methods of Date Class

Introduction

Java is a very powerful object-oriented programming language. It has many predefined classes and libraries which provide various functionalities. There are libraries available that provide functionality for reading and writing data to files and strings to create/provide user interfaces. Java contains the Utility Class Library, which provides utility classes that include generic data structures, string manipulation, etc. Date Class is one of the classes of the java.util. In this blog, we will discuss about the Date Class in Java in detail.

Read More About, Basics of Java

What is a Date Class in Java?

java.util provides the Date Class that is used to represent a specific instant in time with millisecond precision. The Date Class implements a serializable, cloneable, and comparable interface. The class provides a set of constructors and methods to deal with the date and time with java.

Constructors

  • Date(): This is used to create a date object which represents the current date and time.
     
  • Date(long milliseconds): This is used to create a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
     
  • Date(int year, int month, int date) : This has been replaced by Calender.set(year + 1900, month, date) after JDK version 1.1
     
  • Date(int year, int month, int date, int hrs, int min): This has been replaced by Calender.set(year + 1900, month, date, hrs, min) after JDK version 1.1


Code

// import to use the Date Class
import java.util.*;
  
public class Main
{
    public static void main(String[] args)
    {
        Date date1 = new Date();
        System.out.println("Current date : " + date1);
        Date date2 = new Date(2323223232L);
        System.out.println("Date represented : "+ date2 );
    }
}


Output

Current date : Thu Jun 02 13:44:39 GMT 2022
Date represented : Tue Jan 27 21:20:23 GMT 1970

 

Practice it on online java compiler for better understanding.

Methods

  • boolean after(Date date): This method is used to check whether the current date is after the date passed as an argument or not.
     
  • boolean before(Date date): This method is used to check whether the current date is before the date passed as an argument or not.
     
  • int compareTo(Date date): This method compares the current date with the date passed as an argument and returns an integer value. If the current date is equal to the given date, then it returns 0, if the current date is before the given date, then it returns a value less than 0, and if the current date is after the given date, then it returns a value greater than 0.
     
  • getTime() : This method is used to return the number of milliseconds since January 1, 1970, 00:00:00 GMT. it returns a long value.
     
  • setTime(): This method is used to change the current date and time.

 
Code

import java.util.*;
  
public class Main
{
    public static void main(String[] args)
    {
        Date date1 = new Date(2020, 9, 17);
        Date date2 = new Date(); // used to store the current date
        Date date3 = new Date(2024, 1, 3);
    
        System.out.println("Current Date : " + date2);
    
        boolean a = date2.after(date3);
        System.out.println("Date '" + date2 + "' comes after " +
                          " date '"+ date3 + "' : " + a);
  
        boolean b = date2.before(date1);
        System.out.println("Date '" + date2 + "' comes before " +
                          " date '"+ date1 + "' : " + b);
  
        double c = date1.compareTo(date2);
        System.out.println("On comparing '"+date1+"' with '"+date2+"' the result is " +c);
  
        System.out.println("Milliseconds from Jan 1 "+ "1970 to date d1 is " + date1.getTime());
  
        System.out.println("Before setting "+date2);
        date2.setTime(204517433443L);
        System.out.println("After setting "+date2);
    }
}


Output

Current Date : Thu Jun 02 14:28:55 GMT 2022
Date 'Thu Jun 02 14:28:55 GMT 2022' comes after date 'Sun Feb 03 00:00:00 GMT 3924' : false
Date 'Thu Jun 02 14:28:55 GMT 2022' comes before date 'Sun Oct 17 00:00:00 GMT 3920' : true
On comparing 'Sun Oct 17 00:00:00 GMT 3920' with 'Thu Jun 02 14:28:55 GMT 2022' the result is 1.0
Milliseconds from Jan 1 1970 to date d1 is 61561036800000
Before setting Thu Jun 02 14:28:55 GMT 2022
After setting Fri Jun 25 02:23:53 GMT 1976

Display Current Date and Time

We can use the java.time.LocalTime in order to display the current time in hour, minute, second, and nanoseconds. Similarly, we can use the java.time.LocalDate to display the current date.

Code

import java.time.LocalDate;
import java.time.LocalTime;

public class Main {
  public static void main(String[] args) {
    LocalDate date = LocalDate.now(); // Create a date object
    System.out.println("The current date is "+date); // Display the current date
    
    LocalTime time = LocalTime.now(); // Create a time object
    System.out.println("The current time is "+time); // Display the current time
  }
}


Output

The current date is 2022-06-02
The current time is 15:08:30.141123

Formatting Date and Time

Using the DateTimeFormatter class and ofPattern() method which are available in java.time.format.DateTimeFormatter we can format or parse date-time objects.

Code

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; // DateTimeFormatter class

public class Main {
  public static void main(String[] args) {
    
    // create an object to get the date & time
    LocalDateTime date_time_original = LocalDateTime.now();
    
    // create the format in which date & time is to be converted
    DateTimeFormatter format_date_time = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

    // store the current date & time in the desired format in the 
form of string
    String newDateTime = format_date_time.format(date_time_original);
    System.out.println("Formatted Date and Time : " +      newDateTime);
  }
}


Output

Formatted Date and Time: 02-06-2022 15:26:04

You can also read about the Multiple Inheritance in Java.

Frequently Asked Questions

What is the default pattern for dates printed in java?

The default pattern for dates in java is yyyy-mm-dd.
 

Which class can be used to convert a date to a specific instant in time and a set of calendar fields?

The calendar class in Java can be used to convert the date between a specific instant in time and a set of calendar fields.
 

What can be used to print time in nanoseconds?

We can use the java.time.LocalTime in order to display the current time in hour, minute, second, and nanoseconds

Conclusion

In this article, we have extensively discussed the Methods of the Date class in the Java programming language.

After reading about Date Class, are you not feeling excited to read/explore more articles on Java? Don't worry; Coding Ninjas has you covered. To learn about static and instance methods in Java, top 33 questions in Java, and how to print all the permutation of string.

Recommended Readings:

If you wish to enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, and many more, then you should check out our Guided path column at Coding Ninjas Studio. We at Coding Ninjas Studio organize many contests in which you can participate. You can also prepare for the contests and test your coding skills by giving the mock test series available. In case you have just started the learning process, and your dream is to crack major tech giants like Amazon, Microsoft, etc., then you should check out the most frequently asked problems and the interview experiences of your seniors that will surely help you in landing a job in your dream company. 

Do upvote if you find the blogs helpful.

Happy Learning!

Live masterclass