YouTip LogoYouTip

Java Calendar Class

The Calendar class is an abstract class in Java used for handling dates and times, located in the `java.util` package. This class provides a series of methods to manipulate date and time fields (such as year, month, day, hour, minute, etc.), and can perform date calculations and comparisons. ### Why Do We Need the Calendar Class? In Java, although the Date class can also represent dates and times, it has the following limitations: 1. Most methods are deprecated 2. Does not support internationalization 3. Limited date calculation functionality The Calendar class solves these problems, providing more powerful and flexible date and time manipulation capabilities. * * * ## Basic Usage of Calendar Class ### Getting Calendar Instance Since Calendar is an abstract class, we cannot instantiate it directly. The standard way to get a Calendar instance is: ## Instance Calendar calendar =Calendar.getInstance(); This method returns a Calendar instance based on the default time zone and locale (usually GregorianCalendar). ### Setting Date and Time We can use the `set()` method to set various fields of a Calendar object: ## Instance // Set year, month, day calendar.set(2023, Calendar.NOVEMBER, 15); // Set year, month, day, hour, minute, second calendar.set(2023, Calendar.NOVEMBER, 15, 14, 30, 0); Note: Months start from 0, where 0 represents January and 11 represents December. To avoid confusion, it is recommended to use the constants defined in the Calendar class (such as Calendar.JANUARY, Calendar.FEBRUARY, etc.). ### Getting Date and Time Information Use the `get()` method to get various fields from a Calendar object: ## Instance int year = calendar.get(Calendar.YEAR);// Get year int month = calendar.get(Calendar.MONTH);// Get month (0-11) int day = calendar.get(Calendar.DAY_OF_MONTH);// Get day int hour = calendar.get(Calendar.HOUR_OF_DAY);// Get hour (24-hour format) int minute = calendar.get(Calendar.MINUTE);// Get minute int second = calendar.get(Calendar.SECOND);// Get second * * * ## Common Methods of Calendar Class ### Date Calculation The Calendar class provides convenient date calculation methods: ## Instance // Add 10 days to the current date calendar.add(Calendar.DAY_OF_MONTH, 10); // Subtract 3 months from the current month calendar.add(Calendar.MONTH, -3); ### Date Comparison We can use the `compareTo()` method to compare two Calendar objects: ## Instance Calendar cal1 =Calendar.getInstance(); Calendar cal2 =Calendar.getInstance(); cal2.add(Calendar.DAY_OF_MONTH, 1); int result = cal1.compareTo(cal2); // result 0 means cal1 is later than cal2 ### Getting Timestamp You can use the `getTimeInMillis()` method to get the timestamp (in milliseconds) represented by a Calendar object: ## Instance long timestamp = calendar.getTimeInMillis(); You can also use the `getTime()` method to convert it to a Date object: ## Instance Date date = calendar.getTime(); * * * ## Advanced Usage of Calendar Class ### Setting Time Zone We can set a specific time zone for a Calendar object: ## Instance TimeZone timeZone =TimeZone.getTimeZone("America/New_York"); calendar.setTimeZone(timeZone); ### Calendar Field Operations The Calendar class provides the `roll()` method, which can roll a certain field without affecting other fields: ## Instance // Increase month by 1, but won't change the year calendar.roll(Calendar.MONTH, true);// or calendar.roll(Calendar.MONTH, 1); ### Getting the First Day of the Week Different regions have different definitions for the first day of the week (some are Sunday, some are Monday): ## Instance int firstDayOfWeek = calendar.getFirstDayOfWeek(); ### Comprehensive Example ## Instance import java.util.Calendar; import java.util.GregorianCalendar; import java.text.SimpleDateFormat; public class CalendarDemo { public static void main(String[] args){ // 1. Get Calendar instance (default uses current date and time) Calendar calendar =Calendar.getInstance(); // 2. Get values of various fields int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH)+1;// Month starts from 0, need to add 1 int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY);// 24-hour format int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); System.out.printf("Current time: %d year %d month %d day %d:%d:%d%n", year, month, day, hour, minute, second); // 3. Set specific date and time calendar.set(2023, Calendar.MAY, 15, 10, 30, 0);// May 15, 2023 10:30:00 // 4. Use SimpleDateFormat for formatted output SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("Time after setting: "+ sdf.format(calendar.getTime())); // 5. Date operations calendar.add(Calendar.DAY_OF_MONTH, 5);// Add 5 days calendar.add(Calendar.HOUR, -3);// Subtract 3 hours System.out.println("Time after operation: "+ sdf.format(calendar.getTime())); // 6. Compare dates Calendar anotherCalendar =new GregorianCalendar(2023, Calendar.JUNE, 1); System.out.println("Comparison result: "+ (calendar.before(anotherCalendar)?"before":"after")); // 7. Get the day of the week (Sunday=1, Saturday=7) int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); System.out.println("Weekday: "+ getChineseWeekday(dayOfWeek)); } private static String getChineseWeekday(int dayOfWeek){ String[] weekdays ={"", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; return weekdays; } } Output: Current time: 2023 year 5 month 15 day 14:25:36Time after setting: 2023-05-15 10:30:00Time after operation: 2023-05-20 07:30:00Comparison result: beforeTuesday * * * ## Notes on Calendar Class 1. **Months start from 0**: In the Calendar class, months start from 0 (0=January, 11=December), which can easily lead to errors. 2. **Mutability**: Calendar objects are mutable, and modifying one Calendar object will affect all places that reference it. 3. **Thread Safety**: The Calendar class is not thread-safe, and additional synchronization is needed in multi-threaded environments. 4. **Performance**: Frequently creating Calendar instances can affect performance, consider reusing instances. 5. **Time Zone Issues**: Default uses system time zone, cross-time zone applications need special attention. * * * ## Alternatives in Java 8 Starting from Java 8, a new date and time API (`java.time` package) was introduced, providing more modern and easier-to-use date and time handling. If using Java 8 or higher, it is recommended to prioritize the new API: ## Instance // New API to replace Calendar LocalDate date = LocalDate.now(); LocalDateTime dateTime = LocalDateTime.now(); ZonedDateTime zonedDateTime = ZonedDateTime.now(); The new API solves many problems of the Calendar class, including better thread safety, more intuitive API design, and more powerful features. * * * ## Common Methods of Java Calendar Class The following are common methods of the java.util.Calendar class: ### Basic Methods | Method | Description | Example | | --- | --- | --- | | `static Calendar getInstance()` | Get Calendar instance with default time zone and locale | `Calendar cal = Calendar.getInstance()` | | `static Calendar getInstance(TimeZone zone)` | Get Calendar instance with specified time zone | `Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"))` | | `static Calendar getInstance(Locale locale)` | Get Calendar instance with specified locale | `Calendar cal = Calendar.getInstance(Locale.CHINA)` | | `static Calendar getInstance(TimeZone zone, Locale locale)` | Get Calendar instance with specified time zone and locale | `Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"), Locale.CHINA)` | ### Field Constants (Common) | Field | Description | Value Range | | --- | --- | --- | | `Calendar.YEAR` | Year field | - | | `Calendar.MONTH` | Month field | 0-11 (0 represents January) | | `Calendar.DATE` or `Calendar.DAY_OF_MONTH` | Day of month | 1-31 | | `Calendar.DAY_OF_WEEK` | Day of week | 1-7 (1 represents Sunday) | | `Calendar.HOUR` | Hour in 12-hour format | 0-11 | | `Calendar.HOUR_OF_DAY` | Hour in 24-hour format | 0-23 | | `Calendar.MINUTE` | Minute | 0-59 | | `Calendar.SECOND` | Second | 0-59 | | `Calendar.MILLISECOND` | Millisecond | 0-999 | | `Calendar.AM_PM` | AM or PM | 0 (AM) or 1 (PM) | ### Date and Time Operation Methods | Method | Description | Example | | --- | --- | --- | | `int get(int field)` | Get the value of the specified field | `int year = cal.get(Calendar.YEAR)` | | `void set(int field, int value)` | Set the value of the specified field | `cal.set(Calendar.MONTH, 5)` (set to June) | | `void set(int year, int month, int date)` | Set year, month, day | `cal.set(2023, 5, 15)` (June 15, 2023) | | `void set(int year, int month, int date, int hourOfDay, int minute)` | Set year, month, day, hour, minute | `cal.set(2023, 5, 15, 14, 30)` | | `void set(int year, int month, int date, int hourOfDay, int minute, int second)` | Set year, month, day, hour, minute, second | `cal.set(2023, 5, 15, 14, 30, 45)` | | `void add(int field, int amount)` | Add or subtract specified amount of time | `cal.add(Calendar.DATE, 5)` (add 5 days) | | `void roll(int field, int amount)` | Add or subtract time amount without changing larger fields | `cal.roll(Calendar.DATE, 5)` (only changes day field) | ### Time Comparison Methods | Method | Description | Example | | --- | --- | --- | | `boolean after(Object when)` | Check if this Calendar is after the specified time | `cal1.after(cal2)` | | `boolean before(Object when)` | Check if this Calendar is before the specified time | `cal1.before(cal2)` | | `int compareTo(Calendar anotherCalendar)` | Compare the time order of two Calendar objects | `cal1.compareTo(cal2)` | ### Other Utility Methods | Method | Description | Example | | --- | --- | --- | | `long getTimeInMillis()` | Return the time value of this Calendar (milliseconds) | `long millis = cal.getTimeInMillis()` | | `void setTimeInMillis(long millis)` | Set Calendar with given millisecond time value | `cal.setTimeInMillis(1626345600000L)` | | `Date getTime()` | Return a Date object representing this Calendar's time value | `Date date = cal.getTime()` | | `void setTime(Date date)` | Set Calendar's time using given Date | `cal.setTime(new Date())` | | `void clear()` | Clear all field values | `cal.clear()` | | `void clear(int field)` | Clear the value of the specified field | `cal.clear(Calendar.HOUR)` | | `boolean isSet(int field)` | Check if the specified field has been set | `if(cal.isSet(Calendar.YEAR))` |
← Java Localdate ClassJava Date Class β†’