Set a duration in Java

Java 8Object Oriented ProgrammingProgramming

To set a duration, let us declare two objects of Calendar class

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

Set a time for one of the calendar objects

c2.add(Calendar.HOUR, 9);
c2.add(Calendar.MINUTE, 15);
c2.add(Calendar.SECOND, 40);

Now, find the difference between both the time. One would be the current time and another we declared above −

long calcSeconds = (c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000;

The following is an example −

Example

 Live Demo

import java.util.Calendar;
public class Demo {
public static void main(String args[]) {
    Calendar c1 = Calendar.getInstance();
    Calendar c2 = Calendar.getInstance();
    // set hour, minute and second
    c2.add(Calendar.HOUR, 9);
    c2.add(Calendar.MINUTE, 15);
    c2.add(Calendar.SECOND, 40);
    long calcSeconds = (c2.getTimeInMillis() - c1.getTimeInMillis()) / 1000;
    String time = String.format("%02d:%02d:%02d", calcSeconds / 3600, (calcSeconds % 3600) / 60, (calcSeconds % 60));
   System.out.println("Time = "+time);
   }
}

Output

Time= 09:15:40
raja
Updated on 27-Jun-2020 12:42:06

Advertisements