Java Reference
In-Depth Information
The Date Class
With the
Date
class you can create an object that represents a given date and time. You have two ways
to do this using the following constructors:
Method
Description
Date()
Creates an object based on the current time from your computer
clock to the nearest millisecond.
Date(long time)
Creates an object based on the time value in milliseconds since
00:00:00 GMT on January 1, 1970 that is passed as an argument.
With either constructor you create a
Date
object that represents a specific instant in time to the nearest
millisecond. Carrying dates around as the number of milliseconds since the dawn of the year 1970 won't
grab you as being incredibly user-friendly - but we'll come back to how we can interpret a
Date
object
better in a moment. The
Date
class provides three methods for comparing
Date
objects:
Comparison Methods
Description
after
(Date earlier)
Returns
true
if the current object represents a date that's later
than the date represented by the argument
earlier
, and
false
otherwise.
before
(Date later)
Returns
true
if the current object represents a date that's earlier
than the date represented by the argument
later
, and
false
otherwise.
equals
(Object aDate)
Returns
true
if the current object and the argument represent
the same date and time, and
false
otherwise. This implies that
they would both return the same value from
getTime()
.
The
equals()
method returns
true
if two different
Date
objects represent the same date and time.
Since the
hashCode()
method is also implemented for the class, you have all you need to use
Date
objects as keys in a hash table.
Interpreting Date Objects
The
DateFormat
class is an abstract class that you can use to create meaningful
String
representations of
Date
objects. It isn't in the
java.util
package though - it's defined in the package
java.text
. There are four standard representations for the date and the time that are identified by
constants defined in the
DateFormat
class. The effects of these will vary in different countries, because
the representation for the date and the time will reflect the conventions of those countries. The
constants in the
DateFormat
class defining the four formats are: