Wednesday, February 8, 2017

17 Examples of Calendar and Date in Java

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 task simpler, e.g. create an arbitrary date comes easier using new GregorianCalendar(2016, Calendar.JUNE, 11) constructor, as opposed to Date class where the year starts from 1900 and Month was starting from zero. It didn't solve all the problems e.g. 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 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 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. 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 which 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 calculates leap year.

In 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, 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 example to understand how to use it for your daily date and time-related operations.




How to convert Date to Calendar in Java

One of the first thing 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 e.g. 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 doesn'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.

17 Examples of Calendar and Date in Java


How to extract day, month and other fields from Calendar

Once you set the Date to Calendar class, you can use its various get() method 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 Calendar instance. The Java How to Program by Dietel and Dietel also have som more practical examples of accessing date and time-related attributes from Calendar instance.

17 Examples of Calendar in Java


How to add days, month and year to Date

You can use the add() method of Calendar to add or subtract a day, month, year, hour, a 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 the 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 date returned by the Calendar is different after adding and subtracting two days from calendar instance using the add() method. Just remember, to subtract a day, pass a negative value e.g. to subtract two days we passed -2. If you want to subtract just one day, pass -1

17 Examples of Date and Calendar in Java



Java Calendar Example 

Here is our Java program to demonstrate some more example 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 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's value is 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 new Date and Time API of Java 8.

Further Reading
Java Fundamentals, Part 1 and 2
Core Java For the Impatient - Covers Java SE 8
Java Fundamentals: The Java Language


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 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 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)

Thanks for reading this article, if you like this tutorial, please share with your friends and colleagues. If you have any feedback or suggestions then please drop a comment. If you have any interesting example, which is not in this article, feel free to share them with us. 

No comments :

Post a Comment