How Can I Calculate the Difference Between Two Dates and Times in Java?
Dec 12, 2024 pm 01:26 PMCalculating 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. } }
Output when running with the provided input:
Time in seconds: 45 seconds. Time in minutes: 3 minutes.
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte

How does Java's classloading mechanism work, including different classloaders and their delegation models?

Iceberg: The Future of Data Lake Tables

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?

Node.js 20: Key Performance Boosts and New Features
