Java Reference
In-Depth Information
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 millisec-
onds 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).
line#
4
7
10
13
16
19
22
variables
totalMilliseconds
1203183068328
totalSeconds
1203183068
currentSecond
8
totalMinutes
20053051
currentMinute
31
totalHours
334217
currentHour
17
In the sample run, a single digit
8
is displayed for the second. The desirable output
would be
08
. This can be fixed by using a method that formats a single digit with a prefix
0
(see Exercise 6.37).
2.23
✓
✓
How do you obtain the current second, minute, and hour?
Check
Point
Search WWH ::
Custom Search