
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Minutes Between Two Time Instants in Java
In this article, we will calculate the number of minutes between two-time instants using Java. This will be done by using the Instant and Duration classes from the java.time package. We'll create two instances of time, add specific hours and minutes to one of them, and then compute the difference in minutes between the two.
Steps to get minutes between two-time instants
Following are the steps to get minutes between two-time instants ?
- First, import the necessary classes: Duration, Instant, and ChronoUnit from the java.time package.
- Create an instance of the current time using Instant.now().
- Add 5 hours and 10 minutes to the first time instance to create a second time instance.
- Use the Duration.between() method to calculate the difference between the two instants.
- Output the result in minutes using the toMinutes() method.
Java program to get minutes between two-time instants
Below is the Java program to get minutes between two-time instants ?
import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; public class Demo { public static void main(String[] args) { Instant time1 = Instant.now(); Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(10, ChronoUnit.MINUTES); Duration duration = Duration.ofSeconds(13); Instant i = time1.plus(duration); System.out.println("Minutes between two time instants = "+Duration.between(time1, time2).toMinutes()); } }
Output
Minutes between two time instants = 310
Code Explanation
The above program begins by importing the required classes. We then create a current time instance, time1, using Instant.now(). After that, we create time2 by adding 5 hours and 10 minutes to time1 using plus() with ChronoUnit. To get the minutes between the two instants, we use Duration.between(time1, time2) and convert the result into minutes with toMinutes(). Finally, the program prints out the result.