Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Set a duration in Java
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
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
Advertisements
