Java Reference
In-Depth Information
the current second, minute, and hour. Java provides a system-independent encapsulation of
date and time in the
java.util.Date
class, as shown in Figure 8.10.
java.util.Date
class
java.util.Date
+Date()
+Date(elapseTime: long)
Constructs a
Date
object for the current time.
Constructs a
Date
object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String
+getTime(): long
Returns a string representing the date and time.
Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void
Sets a new elapse time in the object.
F
IGURE
8.10
A
Date
object represents a specific date and time.
You can use the no-arg constructor in the
Date
class to create an instance for the current
date and time, the
getTime()
method to return the elapsed time since January 1, 1970, GMT,
and the
toString()
method to return the date and time as a string. For example, the follow-
ing code
java.util.Date date = ;
System.out.println(
"The elapsed time since Jan 1, 1970 is "
+
+
" milliseconds"
);
System.out.println(
new
java.util.Date()
create object
date.getTime()
get elapsed time
date.toString()
);
invoke
toString
displays the output like this:
The elapsed time since Jan 1, 1970 is 1324903419651 milliseconds
Mon Dec 26 07:43:39 EST 2011
The
Date
class has another constructor,
Date(long elapseTime)
, which can be used to
construct a
Date
object for a given time in milliseconds elapsed since January 1, 1970, GMT.
8.6.2 The
Random
Class
You have used
Math.random()
to obtain a random
double
value between
0.0
and
1.0
(excluding
1.0
). Another way to generate random numbers is to use the
java.util.Random
class, as shown in Figure 8.11, which can generate a random
int
,
long
,
double
,
float
, and
boolean
value.
java.util.Random
+Random()
+Random(seed: long)
+nextInt(): int
+nextInt(n: int): int
+nextLong(): long
+nextDouble(): double
+nextFloat(): float
+nextBoolean(): boolean
Constructs a
Random
object with the current time as its seed.
Constructs a
Random
object with a specified seed.
Returns a random
int
value.
Returns a random
int
value between
0
and
n
(excluding
n
).
Returns a random
long
value.
Returns a random
double
value between
0.0
and
1.0
(excluding
1.0
).
Returns a random
float
value between
0.0F
and
1.0F
(excluding
1.0F
).
Returns a random
boolean
value.
F
IGURE
8.11
A
Random
object can be used to generate random values.