Java Reference
In-Depth Information
< Day Day Up >
Puzzle 61: The Dating Game
The following program exercises some basic features of the
Date
and
Calendar
classes. What does
it print?
import java.util.*;
public class DatingGame {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(1999, 12, 31); // Year, Month, Day
System.out.print(cal.get(Calendar.YEAR) + " ");
Date d = cal.getTime();
System.out.println(d.getDay());
}
}
Solution 61: The Dating Game
This program creates a
Calendar
instance that appears to represent New Year's Eve, 1999, and
prints the year followed by the day. It seems that the program should print
1999 31
, but it doesn't; it
prints
2000 1
. Could this be the dreaded Y2K problem?
No, it's something much worse: It is the dreaded
Date
/
Calendar
problem. When the Java platform
was first released, its only support for calendar calculations was the
Date
class. This class was
limited in power, especially when it came to support for internationalization, and it had a basic
design flaw:
Date
instances were mutable. In release 1.1, the
Calendar
class was added to the
platform to rectify the shortcomings of
Date
; most
Date
methods were deprecated. Unfortunately,
this only made a bad situation worse. Our program illustrates a few of the problems with the
Date
and
Calendar
APIs.
Search WWH ::
Custom Search