Get Milliseconds Between Dates in Java



In this article, we will learn to get milliseconds between dates in Java. We will be using the LocalDateTime class from java.time package and ChronoUnit.MILLIS of java.time.temporal package.

ChronoUnit is an enum that is part of Java date and time API which represents a unit of time that is days, hours, minutes etc.

Here, the MILLIS is a unit that represents the concept of a millisecond.

Problem Statement

Write a program in Jave to get milliseconds between dates. Below is the representation ?

Input

Date One = 2024-09-04T05:40:19.817038951
Date Two = 2019-04-10T11:20

Output

Milliseconds between two dates = -170533219817

Steps to get milliseconds between dates

Following are the steps to get milliseconds between dates ?

  • Import the LocalDateTime class and ChronoUnit enum.
  • Create date instances by using LocalDateTime.now() for the current date and time, and LocalDateTime.of() to create a specific date.
  • We will calculate milliseconds to do so we will be using MILLIS.between() to find the difference in milliseconds between the two dates.
  • Display the results.

Java program to get milliseconds between dates

Below is the Java program to get milliseconds between dates?

import java.time.LocalDateTime;
import static java.time.temporal.ChronoUnit.MILLIS;
public class Demo {
    public static void main(String[] argv) {
        LocalDateTime dateOne = LocalDateTime.now();
        LocalDateTime dateTwo = LocalDateTime.of(2019, 4, 10, 11,20);
        System.out.println("Date One = "+dateOne);
        System.out.println("Date Two = "+dateTwo);
        long res = MILLIS.between(dateOne, dateTwo);
        System.out.println("Milliseconds between two dates = " + res);
    }
}

Output

Date One = 2019-04-12T11:18:29.654947300
Date Two = 2019-04-10T11:20
Milliseconds between two dates = -172709654

Code Explanation

In this program, we start by importing the LocalDateTime class from java.time to handle date and time, and MILLIS from java.time.temporal.ChronoUnit to measure time in milliseconds. We create two LocalDateTime instances: dateOne for the current date and time using LocalDateTime.now(), and dateTwo for a specific date using LocalDateTime.of() method.

The program calculates the difference in milliseconds between dateOne and dateTwo using the MILLIS.between() method. Finally, both the dates and the difference in the calculated milliseconds are printed to the console.

Updated on: 2024-09-05T11:22:45+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements