The java.util.Calendar class was added in Java on JDK 1.4 in an attempt to fix some flaws of the java.util.Date class. It did make some tasks simpler, e.g. create an arbitrary date comes easier using the new GregorianCalendar(2016, Calendar.JUNE, 11) constructor, as opposed to the Date class where the year starts from 1900 and the Month was starting from zero. It didn't solve all the problems like mutability and thread-safety of Date class still remains, but it does make life easier at that time. Now with Java 8 everything related to Date and Time has become super easy and consistent but unfortunately, it will take another 5 to 10 years before the older version of Java goes away. Don't believe me, there are still applications running on JDK 1.5 which was released 12 years ago. The bottom line is it's still important to know about the Date and Calendar in Java.
The java.util.Calendar class is an abstract class and you obtain the instance of a Calendar local to your timezone and Locale by calling the getInstance() method of java.util.Calendar class.
The java.util.Calendar class is an abstract class and you obtain the instance of a Calendar local to your timezone and Locale by calling the getInstance() method of java.util.Calendar class.
This method generally returns an instance of GregorianCalendar class except when your JVM is running with Japanese and Thai Locale where it returns different instances of Calendar e.g. BuddhistCalendar for Thai ("th_TH") and JapaneseImperialCalendar for Japanese ("ja_JP") Locale.
The Gregorian calendar is the calendar that is used today. It came into effect on October 15, 1582, in some countries and later in other countries. It replaces its predecessor the Julian calendar and 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian) due to differences in how Julian and GregorianCalendar calculate leap year.
In the Julian calendar, every four years is a leap year. In the Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400 (removing 3 leap years (or 3 days) for every 400 years). Furthermore, the Julian calendar considers the first day of the year as march 25th, instead of January 1st.
The Calendar class provides support for extracting date and time fields from a Date e.g. YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, SECOND, MILLISECOND; as well as manipulating these fields e.g. by adding and subtracting days from a date and calculating next or previous day, month or year (see), etc.
In this article, I'll share some useful Calendar examples to understand how to use them for your daily date and time-related operations.
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
One of the first things a Java developer should know while using Calendar is the conversion between Date and Calendar classes. Similar to how you converted Timestamp to Date, here also we can use the getTime() and setTime() method, albeit this time they are from the java.util.Calendar class.
By default, when you get the Calendar it has today's date, to set to any arbitrary date just call the Calendar.setTime(date), now you have the right Date set to your calendar and you can use the Calendar's get() and add() method to extract different fields and manipulate them as well like day, month and year.
Similarly, to convert a java.util.Calendar back to the java.util.Date just call the getTime() method of Calendar class as shown in the following example:
Super easy right? but only if you know. It's not very obvious from API as Calendar doesn't accept a Date value in the constructor and the name getTime() and setTime() also don't indicate that they return or accept a Date value. If you want to learn more about Date and Calendar classes in Java, I suggest reading Core Java Volume 1 - Fundamentals by Cay S. Horstmann, one of the better books to learn core Java concepts.
The Gregorian calendar is the calendar that is used today. It came into effect on October 15, 1582, in some countries and later in other countries. It replaces its predecessor the Julian calendar and 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian) due to differences in how Julian and GregorianCalendar calculate leap year.
In the Julian calendar, every four years is a leap year. In the Gregorian calendar, a leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not divisible by 400 (removing 3 leap years (or 3 days) for every 400 years). Furthermore, the Julian calendar considers the first day of the year as march 25th, instead of January 1st.
The Calendar class provides support for extracting date and time fields from a Date e.g. YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, SECOND, MILLISECOND; as well as manipulating these fields e.g. by adding and subtracting days from a date and calculating next or previous day, month or year (see), etc.
In this article, I'll share some useful Calendar examples to understand how to use them for your daily date and time-related operations.
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
How to convert Date to Calendar in Java
One of the first things a Java developer should know while using Calendar is the conversion between Date and Calendar classes. Similar to how you converted Timestamp to Date, here also we can use the getTime() and setTime() method, albeit this time they are from the java.util.Calendar class.By default, when you get the Calendar it has today's date, to set to any arbitrary date just call the Calendar.setTime(date), now you have the right Date set to your calendar and you can use the Calendar's get() and add() method to extract different fields and manipulate them as well like day, month and year.
Date date= new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date);
Similarly, to convert a java.util.Calendar back to the java.util.Date just call the getTime() method of Calendar class as shown in the following example:
Date d = cal.getTime();
Super easy right? but only if you know. It's not very obvious from API as Calendar doesn't accept a Date value in the constructor and the name getTime() and setTime() also don't indicate that they return or accept a Date value. If you want to learn more about Date and Calendar classes in Java, I suggest reading Core Java Volume 1 - Fundamentals by Cay S. Horstmann, one of the better books to learn core Java concepts.
How to extract day, month and other fields from Calendar
Once you set the Date to Calendar class, you can use its various get() methods to extract different fields e.g. Calendar.get(Calendar.DAY_OF_MONTH) to get the current day. Here is a list of Calendar field you can use with get() and add() method:get(Calendar.DAY_OF_WEEK): returns 1 (Calendar.SUNDAY) to 7 (Calendar.SATURDAY). get(Calendar.YEAR): returns year get(Calendar.MONTH): returns 0 (Calendar.JANUARY) to 11 (Calendar.DECEMBER). get(Calendar.DAY_OF_MONTH), get(Calendar.DATE): 1 to 31 get(Calendar.HOUR_OF_DAY): 0 to 23 get(Calendar.MINUTE): 0 to 59 get(Calendar.SECOND): 0 to 59 get(Calendar.MILLISECOND): 0 to 999 get(Calendar.HOUR): 0 to 11, to be used together with Calendar.AM_PM. get(Calendar.AM_PM): returns 0 (Calendar.AM) or 1 (Calendar.PM).
This is very important to know because once you know that you can extract any Date or time-related field from the Calendar instance. The Java How to Program by Dietel and Dietel also have some more practical examples of accessing date and time-related attributes from the Calendar instance.
How to add Days, Months, and Years to Date
You can use the add() method of Calendar to add or subtract a day, month, year, hour, minute, or any other field from Date in Java. Yes, the same method is used for adding and subtracting, you just need to pass a negative value for subtraction e.g. -1 to subtract one day and get yesterday's day as shown in the following example:cal2.add(Calendar.DAY_OF_MONTH, 1); d = cal2.getTime(); System.out.println("date after adding one day (tomorrow) : " + d); cal2.add(Calendar.DAY_OF_MONTH, -2); d = cal2.getTime(); System.out.println("date after subtracting two day (yesterday) : " + d); Output date after adding one day (tomorrow): Wed Jun 22 00:00:00 IST 2016 date after subtracting two days (yesterday): Mon Jun 20 00:00:00 IST 2016
You can see that the value of the Date returned by the Calendar is different after adding and subtracting two days from the calendar instance using the add() method. Just remember, to subtract a day, pass a negative value, for example, to subtract two days we passed -2. If you want to subtract just one day, pass -1
Java Calendar Example
Here is our Java program to demonstrate some more examples of Calendar class in Java.import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /* * Java Program to show how to use Calendar to get a different date and * time-related attribute. * This program contains multiple how to do examples of Calendar class * to teach you how * to get day, month, year, hour, minute or any other date and time * realted attributes from * Calendar instance. */ public class Main { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); // returns GregorianCalendar except Japan and Thailand // Example 1 - get the year from Calendar System.out.println("Year : " + cal.get(Calendar.YEAR)); // Example 2 - get the month from Calendar System.out.println("Month : " + cal.get(Calendar.MONTH)); // Example 3 - get the Day of month from Date and Calendar System.out.println("Day of Month : " + cal.get(Calendar.DAY_OF_MONTH)); // Example 4 - get the Day of Week from Date System.out.println("Day of Week : " + cal.get(Calendar.DAY_OF_WEEK)); // Example 5 - get the Day of year from Date System.out.println("Day of Year : " + cal.get(Calendar.DAY_OF_YEAR)); // Example 6 - get the Week of Year from Calendar System.out.println("Week of Year : " + cal.get(Calendar.WEEK_OF_YEAR)); // Example 7 - get the Week of Month from Date System.out.println("Week of Month : " + cal.get(Calendar.WEEK_OF_MONTH)); // Example 8 - get the hour from time System.out.println("Hour : " + cal.get(Calendar.HOUR)); // Example 9 - get the AM PM from time System.out.println("AM PM : " + cal.get(Calendar.AM_PM)); // Example 10 - get the hour of the day from Calendar System.out.println("Hour of the Day : " + cal.get(Calendar.HOUR_OF_DAY)); // Example 11 - get the minute from Calendar System.out.println("Minute : " + cal.get(Calendar.MINUTE)); // Example 12 - get the Second from Calendar System.out.println("Second : " + cal.get(Calendar.SECOND)); System.out.println(); // Example 13 - converting Date to Calendar Date date= new Date(); Calendar cal1 = Calendar.getInstance(); cal.setTime(date); // Example 14 - Creating GregorianCalendar of specific date Calendar cal2 = new GregorianCalendar(2016, Calendar.JUNE, 21); // Example 15 - Converting Calendar to Date Date d = cal2.getTime(); System.out.println("date from Calendar : " + d); // Example 16 - adding 1 day into date cal2.add(Calendar.DAY_OF_MONTH, 1); d = cal2.getTime(); System.out.println("date after adding one day (tommorrow) : " + d); // Example 17 - subtracting a day from day cal2.add(Calendar.DAY_OF_MONTH, -2); d = cal2.getTime(); System.out.println("date after subtracting two day (yesterday) : " + d); } } Output Year: 2016 Month: 5 Day of Month: 17 Day of Week: 6 Day of Year: 169 Week of Year: 25 Week of Month: 3 Hour: 4 AM PM: 1 Hour of the Day: 16 Minute: 24 Second: 37 date from Calendar : Tue Jun 21 00:00:00 SGT 2016 date after adding one day (tommorrow) : Wed Jun 22 00:00:00 SGT 2016 date after subtracting two day (yesterday) : Mon Jun 20 00:00:00 SGT 2016
That's all about how to use the Calendar class in Java. It's a useful class for extracting and manipulating Date and time-related fields in Java 6 and Java 7 but with Java 8 it values are diminished. You should only use this class if you are not running in Java 8. In Java 8 you should use the LocalDate methods to extract date related values, and LocalTime's time-related methods to extract time values e.g. hour, minutes, and seconds. You can also read Java 8 in Action to learn more about the new Date and Time API of Java 8.
Other Date and Time tutorials you may like:
- 20 Essential Examples of Date and Time API of Java 8? (tutorial)
- How to parse String to LocalDateTime in Java 8? (tutorial)
- How to convert java.util.Date to java.sql.Timestamp in JDBC? (tutorial)
- How to parse String to LocalDateTime in Java 8? (tutorial)
- How to get the current date and time in Java 6? (tutorial)
- How to calculate the difference between two dates in Java? (example)
- How to convert String to LocalDateTime in Java 8? (example)
- How to compare two dates in Java? (tutorial)
- How to convert Date to LocalDateTime in Java 8? (tutorial)
- How to get the current Timestamp value in Java? (tutorial)
- How to parse String to Date using JodaTime library? (example)
- How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)
- How to convert java.util.Date to java.time.LocalDateTime in Java 8? (tutorial)
No comments:
Post a Comment