All-In-One Gregorian Calendar Java Guide including Example

Learn how to use the Gregorian Calendar java class and an example. How you can get today’s date, the day of the week, and manipulate dates.

Card image cap

In this article, we will look at dates using the Gregorian Calendar java class and an example. We will see how you can get Today’s Date, how to get the day of the week, and how you can manipulate dates to get next month, next year.

The GregorianCalendar is a java class that extends from the Calendar class and provides the standard calendar system adopted by most of the world. See the official java 8 documentation here

You could use the only Date to handle and work with dates; however, you will miss all internationalization support, like other time zones support. Plus, Date doesn’t offer any functionality to operate with dates, like adding a month or adding 25 days. In case you need to work with dates or time zone support, you will need GregorianCalendar or any of the other Calendar subclasses that offer calendar support.

Another useful operation is formatting. On many occasions, when working with dates, you will need to modify the format. You might need to display the day of the month as a two-digit number, display the month using the abbreviation or using a number, etc. This article will also cover how to format Gregorian calendar with java code example.

Let’s get started!

Get Today’s date using Gregorian Calendar.

Initially, we will start by getting Today’s Date using the gregorian calendar. We will do that by creating a GregorianCalendar instance, which will give us access to all the calendar functionality. Next, we need to call the .getTime() method, which will return a Date object representing Today. This method has inherited this method from the parent Calendar class.

Let’s see how this looks in java code:

import java.util.Date;
import java.util.GregorianCalendar;

public class Main {

    public static void main(String[] args){
       GregorianCalendar gregorianCalendar = new GregorianCalendar();
       Date todayDate = gregorianCalendar.getTime();

       System.out.println("Today's date: "+ todayDate);
       System.out.println("Today's date in milliseconds: " + todayDate.getTime());
    }
}

Output:

Today's date: Sat Dec 12 11:09:24 GMT 2020
Today's date in milliseconds: 1607771364267

Note that by default, GregorianCalendar will use the time zone where you are.

Get the day of the week using Gregorian Calendar.

Now we will see how you can use the gregorian calendar class along with the SimpleDateFormat, to get the day of the week from a given date. For this example, we will convert 3-December-2020 . Please note that the first month in the gregorian calendar is January which is 0; therefore December is 11

GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.DAY_OF_MONTH, 9);
calendar.set(Calendar.MONTH,11);
calendar.set(Calendar.YEAR,2020);

SimpleDateFormat formatter = new SimpleDateFormat("EEEEEE");
String dayOfWeek = formatter.format(calendar.getTime());
System.out.println(dayOfWeek);

Output:

Wednesday

Operations with Gregorian Calendar

So far, we have seen how to get Today. Let’s now see how we can manipulate a date. Using GregorianCalendar, you can modify any field of the Date: month, day, year, hour, minute, etc. For instance, let’s add one month to the current Date:

GregorianCalendar gregorianCalendar = new GregorianCalendar();
Date today = gregorianCalendar.getTime();

gregorianCalendar.set(Calendar.MONTH,gregorianCalendar.get(Calendar.MONTH)+1);

System.out.println("Today's date: " + today);
System.out.println("Next month date: " + gregorianCalendar.getTime());

Output:

Today's date: Sat Dec 12 11:36:57 GMT 2020
Next month date: Tue Jan 12 11:36:57 GMT 2021

As you can see, since the current Date was in December, adding one month will return a next year date. You can use the same mechanism to modify any other field. You can find here a list of all fields that the Calendar class provides.

Convert Gregorian Calendar to Date

Next, let’s see another used operation: converting the gregorian calendar to Date. What that means precisely is converting a gregorian calendar to the format: dd-mmm-yy, for instance’ 04-Apr-2020′. This operation can be useful when you want save a date to a database or a file.

GregorianCalendar gregorianCalendar = new GregorianCalendar();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-YY");
String dateFormated = dateFormat.format(gregorianCalendar.getTime());
System.out.println(dateFormated);

Output:

12-Dec-20

First, you need to create a GregorianCalendar instance and a SimpleDateFormat instance, which will hold the new format to use. Secondly, you need to call the .format() method, part of the SimpleFormatDate class, to convert the date to the desired formatted string.

The string or pattern used when you create the SimpleDateFormat will define the date format. Let’s see a few more date pattern examples.

"dd-MM-YY"         -> "13-12-20"
"dd-MM-YYYY"       -> "13-12-2020"
"yyyy-MM-dd"       -> "2020-12-13"
"EEEEE yyyy-MM-dd" -> "Sunday 2020-12-13"

Find here a list with all the pattern letters available

Format Gregorian Calendar Date example

Find below a complete executable example of how to format a Gregorian calendar date:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
	public static void main(String[] args){

        Date today = new GregorianCalendar().getTime();
        String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(today);
        System.out.println(formattedDate);

    }
}

Output:

2020-12-13

Convert Calendar to GregorianCalendar

In some cases, you might have a Calendar object and want to convert a Calendar object to a GregorianCalendar object. Since there are several concrete subclasses of the class Calendar like BuddhistCalendar and JapaneseImperialCalendar, only casting is not entirely safe. Therefore, you will need to use instanceof before casting. See below how this will work:

    public static GregorianCalendar convert(Calendar calendar){
        if(calendar instanceof GregorianCalendar){
            return (GregorianCalendar) calendar;
        }else{
            return new GregorianCalendar();
        }
    }

Conclusion

In conclusion, in this article, we have seen some operations that the gregorian calendar java class provides an example. The key benefit of the GregorianCalendar class is all calendar support, so you can operate with dates without worrying about leap years and other complex calculations. It can be beneficial when working with dates.

I hope you enjoy the article and find it useful. Thank you so much for reading and supporting this blog.

Happy coding!

More Interesting Articles

Learn Ethical Hacking From Scratch Course

Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java