Home > Java > javaTutorial > How Can I Calculate the Difference Between Two Dates and Times in Java?

How Can I Calculate the Difference Between Two Dates and Times in Java?

DDD
Release: 2024-12-12 13:26:17
Original
443 people have browsed it

How Can I Calculate the Difference Between Two Dates and Times in Java?

Calculating Date/Time Difference in Java

In Java, you can determine the time difference between two dates by parsing them into Date objects and using the getTime() method.

Here's a code snippet to calculate the difference between two dates:

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

class DateTimeDifference {

    public static void main(String[] args) {
        String dateStart = "11/03/14 09:29:58";
        String dateStop = "11/03/14 09:33:43";

        // Custom date format
        SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");

        Date d1 = null;
        Date d2 = null;
        try {
            d1 = format.parse(dateStart);
            d2 = format.parse(dateStop);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // Get the difference in milliseconds
        long diff = d2.getTime() - d1.getTime();
        
        // Convert milliseconds to seconds using TimeUnit
        long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
        
        System.out.println("Time in seconds: " + seconds + " seconds.");
        System.out.println("Time in minutes: " + minutes + " minutes.");

        // Note: Java does not have a built-in method to directly calculate the difference in hours.
        // You can obtain the hours value by performing manual calculations.
    }
}
Copy after login

Output when running with the provided input:

Time in seconds: 45 seconds.
Time in minutes: 3 minutes.
Copy after login

The above is the detailed content of How Can I Calculate the Difference Between Two Dates and Times in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template