Java Reference
In-Depth Information
You can invoke
System.currentTimeMillis()
to return the current time.
Key
Point
The problem is to develop a program that displays the current time in GMT (Greenwich Mean
Time) in the format hour:minute:second, such as 13:19:8.
The
currentTimeMillis
method in the
System
class returns the current time in mil-
liseconds elapsed since midnight, January 1, 1970 GMT, as shown in Figure 2.2. This time
is known as the
UNIX epoch.
The epoch is the point when time starts, and
1970
was the year
when the UNIX operating system was formally introduced.
VideoNote
Use operators / and %
currentTimeMillis
UNIX epoch
Elapsed
time
Time
UNIX epoch
01-01-1970
00:00:00 GMT
Current time
System.currentTimeMillis()
F
IGURE
2.2
The
System.currentTimeMillis()
returns the number of milliseconds
since the UNIX epoch.
You can use this method to obtain the current time, and then compute the current second,
minute, and hour as follows.
1. Obtain the total milliseconds since midnight, January 1, 1970, in
totalMilliseconds
by invoking
System.currentTimeMillis()
(e.g.,
1203183068328
milliseconds).
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.7 gives the complete program.
L
ISTING
2.7
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
Search WWH ::
Custom Search