How to get Date and Time in Java?

Published on Aug 09,2019 2.9K Views

How to get Date and Time in Java?

edureka.co

Java provides the Date class which constitutes the current date and time. This class is available in java.util package. Let us dig a bit deeper and understand how Date and Time in Java can be set.

The topics that we will focus on are enumerated as follows:

Let’s begin!

Constructor and Methods of the Date Class

The Date class works with two constructors:

Constructors:

Date( ):
This constructor will initialize the object with the current date and time.

Date(long millisec):
This constructor accepts an argument that equals the number of milliseconds that have passes by since midnight, January 1, 1970.

Methods of Date class:

There are several methods provided in the Date class.

Object clone( ):
This method duplicates the invoked Date object.

boolean before(Date date):
It returns true if the invoked ‘Date’ object contains a ‘date’ that is earlier than the one specified by the value in – date, or else, it returns false.

boolean after(Date date):
It returns true if the invoked ‘Date’ object contains a ‘date’ that is later than the one specified by date, or else, it returns false.

boolean equals(Object date):
It returns true if the invoked Date object contains the same time and date as the one specified by ‘date’, else, it returns false.

long getTime( ):
It returns the number of milliseconds that have passed by since January 1, 1970.

int compareTo(Object obj):
It operates identically to compareTo(Date) if ‘obj’ is of class Date. Otherwise, it throws a ClassCastException.

int hashCode( ):
It returns a hash code for the invoked object.

void setTime(long time):
It sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970.

String toString( ):
Converts the invoked Date object into a string and returns the result.

Now, Let’s move on with Java Dates.

Java Dates

Java does not provide us with a built-in Date class. We have to import it from the java.util package. The package provides us with the various date and time classes.
Here is a list:

ClassDescription

Local Date

It represents a date (year, month, day (YYYY-MM-dd))

Local Time

It represents time (hour, minute, second and milliseconds (HH-mm-ss-zzz))

Date Time Formatter

It is the formatter for displaying and parsing date-time objects

Local Date Time

It represents both date and time (YYYY-MM-dd-HH-mm-ss.zzz)

Now, moving on, let’s see how do we get the current date and time?

How to get the current date?

To display the current date, import the java.time.LocalDate class. Below listed is an example.

import java.time.LocalDate;
public class Example {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now();
System.out.println(myObj);
}

Output:
2019-08-09

In the same manner, if you wish to get the current time, here is an example.

How to fetch current time?

Example:

import java.time.LocalTime;
public class Example2 {
public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}
}

Output:
15:38:17.483594

Moving further, if you wish to fetch current date and time together, Java provides you with LocalDateTime method. Here is an example:

How to get current date and time?

package Edureka;

import java.time.LocalDateTime;
public class Example {
public static void main(String[] args) {
LocalDateTime myObj = LocalDateTime.now();
System.out.println(myObj);
}
}

Output:

2019-08-08T18:13:34.269

Now, if you want to display the date and time differently, or in different formats, we have a method called: ofPattern() method.

Date and Time Formatting

In this segment, you have the freedom to display the format of both date and time as per your requirement.
Example:

package Edureka;

import java.time.LocalDateTime; 
// Import the LocalDateTime class 
import java.time.format.DateTimeFormatter; 
// Import the DateTimeFormatter class 
public class Aggregation { public static void main(String[] args) 
{ 
LocalDateTime myDateObj = LocalDateTime.now(); 
System.out.println("Output with previous format: " + myDateObj); 
DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("DD-MM-YYY HH:mm:ss"); 
String formattedDate = myDateObj.format(myFormatObj); 
System.out.println("Output After formatting: " + formattedDate); 
} 
}

Output:

Output with previous format: 2019-08-08T17:38:09.419
Output After formatting: 08-08-2019 17:38:09

This brings us to the end of this article where we have learned Java date and time with various examples. Hope you are clear with all that has been shared with you in this tutorial.

If you found this article on “Date and Time in Java” relevant, check out the Edureka Java Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

We are here to help you with every step on your journey, and come up with a curriculum which is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

If you come across any questions, feel free to ask all your questions in the comments section of “Date and Time in Java” and our team will be glad to answer.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework