Java的Date和Calendar

Published on 2017 - 02 - 19

The GregorianCalendar Class of the Java Library

The Date class is not very useful for manipulating dates. The designers of the Java library take the point of view that a date description such as “December 31, 1999, 23:59:59” is an arbitrary convention, governed by a calendar. This particular description follows the Gregorian calendar, which is the calendar used in most countries of the world. The same point in time would be described quite differently in the Chinese or Hebrew lunar calendars, not to mention the calendar used by your customers from Mars.

The library designers decided to separate the concerns of keeping time and attaching names to points in time. Therefore, the standard Java library contains two separate classes: the Date class, which represents a point in time, and the GregorianCalendar class, which expresses dates in the familiar calendar notation. In fact, the GregorianCalendar class extends a more generic Calendar class that describes the properties of calendars in general. The standard Java library also contains implementations of the Thai Buddhist and Japanese imperial calendar.

Actually, the Date class has methods such as getDay, getMonth, and getYear, but these methods are deprecated. A method is deprecated when a library designer realizes that the method should have never been introduced in the first place.

These methods were a part of the Date class before the library designers realized that it makes more sense to supply separate calendar classes. When the calendar classes were introduced, the Date methods were tagged as deprecated. You can still use them in your programs, but you will get unsightly compiler warnings if you do. It is a good idea to stay away from using deprecated methods because they may be removed in a future version of the library.

The job of a calendar is to compute attributes, such as the date, weekday, month, or year, of a certain point in time. To query one of these settings, use the get method of the GregorianCalendar class. To select the item that you want to get, pass a constant defined in the Calendar class, such as Calendar.MONTH or Calendar.DAY_OF_WEEK:

GregorianCalendar now = new GregorianCalendar();
int month = now.get(Calendar.MONTH);
int weekday = now.get(Calendar.DAY_OF_WEEK);

To change the state, call the set method:

deadline.set(Calendar.YEAR, 2001);
deadline.set(Calendar.MONTH, Calendar.APRIL);
deadline.set(Calendar.DAY_OF_MONTH, 15);

Reference