Java Reference
In-Depth Information
2. Obtain the total seconds totalSeconds by dividing totalMilliseconds by 1000
(e.g., 1203183068328 milliseconds / 1000 1203183068 seconds).
=
3. Compute the current second from totalSeconds % 60 (e.g., 1203183068 seconds
% 60 8 , which is the current second).
=
4. Obtain the total minutes totalMinutes by dividing totalSeconds by 60 (e.g.,
1203183068 seconds / 60 20053051 minutes).
=
5. Compute the current minute from totalMinutes % 60 (e.g., 20053051 minutes %
60 31 , which is the current minute).
=
6. Obtain the total hours totalHours by dividing totalMinutes by 60 (e.g.,
20053051 minutes / 60 334217 hours).
=
7. Compute the current hour from totalHours % 24 (e.g., 334217 hours % 24
=
17 ,
which is the current hour).
Listing 2.6 gives the complete program.
L ISTING 2.6 ShowCurrentTime.java
1 public class ShowCurrentTime {
2
public static void main(String[] args) {
3
// Obtain the total milliseconds since midnight, Jan 1, 1970
4
long totalMilliseconds = System.currentTimeMillis();
totalMilliseconds
5
6
// Obtain the total seconds since midnight, Jan 1, 1970
7
long totalSeconds = totalMilliseconds / 1000 ;
totalSeconds
8
9
// Compute the current second in the minute in the hour
10
long currentSecond = totalSeconds % 60 ;
currentSecond
11
12
// Obtain the total minutes
13
long totalMinutes = totalSeconds / 60 ;
totalMinutes
14
15
// Compute the current minute in the hour
16
long currentMinute = totalMinutes % 60 ;
currentMinute
17
18
// Obtain the total hours
19
long totalHours = totalMinutes / 60 ;
totalHours
20
21
// Compute the current hour
22
long currentHour = totalHours % 24 ;
currentHour
23
24 // Display results
25 System.out.println( "Current time is " + currentHour + ":"
26 + currentMinute + ":" + currentSecond + " GMT" );
27 }
28 }
preparing output
Current time is 17:31:8 GMT
Line 4 invokes System.currentTimeMillis() to obtain the current time in milliseconds
as a long value. Thus, all the variables are declared as the long type in this program. The seconds,
minutes, and hours are extracted from the current time using the / and % operators (lines 6-22).
 
Search WWH ::




Custom Search