Announcing Bito’s free open-source sponsorship program. Apply now

Get high quality AI code reviews

Java Gregorian Calendar Example: Java Explained

Table of Contents

The Gregorian calendar is used in many countries around the world to define dates and times. It is based upon a mathematical system of leap years, allowing for accurate time measurements. Java includes a GregorianCalendar class, part of the java.util package, which enables developers to use and manipulate dates and times in a variety of ways. In this article, we’ll take a look at how to use the GregorianCalendar class in Java applications.

What is the Gregorian Calendar?

The Gregorian calendar is a system for organizing time that was devised in 1582 by Pope Gregory XIII and adopted to replace the Julian calendar. It sets specific dates for Easter and other holidays, and it has been adopted worldwide as the global standard of timekeeping. The Gregorian Calendar is based on 12 months with 365 days, with an extra day added every fourth year (known as a “Leap Year”).

The Gregorian calendar is the most widely used calendar in the world today, and it is the official calendar of most countries. It is also used by many religious organizations, including the Roman Catholic Church, to determine the dates of religious holidays. The Gregorian calendar is also used to calculate the age of the Earth, as well as the dates of astronomical events such as eclipses and solstices.

How Does the Gregorian Calendar Work?

The Gregorian calendar uses a complicated series of calculations to determine which days are leap years, so that it can accurately calculate each month’s length. Generally speaking, a year is a leap year if it is divisible by four, unless it is divisible by 100 and not divisible by 400. The Gregorian calendar attempts to keep time with the seasonal pattern of the earth, so that related dates are observed in the same season each year.

The Gregorian calendar is the most widely used calendar in the world today. It was first introduced in 1582 by Pope Gregory XIII, and it replaced the Julian calendar, which had been in use since 45 BC. The Gregorian calendar is based on a 400-year cycle, with 97 leap years occurring during that time. This means that the calendar is accurate to within one day every 3236 years.

Creating a Java Gregorian Calendar Object

Creating an instance of the GregorianCalendar class is easy. Simply provide the following parameters in your constructor: the current year, month, and day. For example:

GregorianCalendar gcal = new GregorianCalendar(2018, 2, 22);// This creates a Gregorian Calendar object representing the date March 22, 2018.

You can also set the time zone for the Gregorian Calendar object using the setTimeZone() method.

The Gregorian Calendar object is useful for performing calculations on dates, such as determining the number of days between two dates or the day of the week for a given date. It is also useful for formatting dates into strings for display purposes.

Accessing Date and Time Information from a Gregorian Calendar Object

Once a Gregorian Calendar object has been constructed, you can access the various components of the date and time using various methods provided by the class. For example, you can retrieve the current month using the get(Calendar.MONTH) method, which will return an integer representing the current month. Here are some other Calendar constants you can use to access different components of a GregorianCalendar object:

  • Calendar.YEAR: Integer representing the current year
  • Calendar.MONTH: Integer representing the current month (January = 0)
  • Calendar.DAY_OF_MONTH: Integer representing the current day of the month
  • Calendar.HOUR_OF_DAY: Integer representing the current hour (24-hour clock)
  • Calendar.MINUTE: Integer representing the current minute
  • Calendar.SECOND: Integer representing the current second
  • Calendar.MILLISECOND: Integer representing the current millisecond
  • Calendar.DAY_OF_WEEK: Integer representing the current day of the week (Sunday = 1)

Manipulating Dates and Times in Java

The GregorianCalendar class also provides methods for manipulating dates and times. You can call these directly on an instance of a GregorianCalendar object. Some of the more commonly used manipulation methods include:

  • add(): Add an offset, in terms of years, months, or days, to any component of a date (i.e. add(Calendar.MONTH, 3) to add three months).
  • roll(): Like add(), but will only increment or decrement one component at a time (i.e. roll(Calendar.YEAR, 1) increments the year by one).
  • set(): Set any component of a date to an exact value (i.e set(Calendar.DAY_OF_MONTH, 15)).
  • getTimeInMillis(): Return the current time represented by this Gregorian Calendar as a long value.
  • setTimeInMillis(): Set the current time represented by this Gregorian Calendar using a long value.
  • getTime(): Return the current date represented by this Gregorian Calendar as a Date object.

Using the GregorianCalendar Class to Format Output

The GregorianCalendar class has several formatting methods which enable you to display dates and times in various formats. The two most commonly used are:

  • getTimeInstance(): Return an instance of DateFormat for formatting dates according to the user’s desired time format.
  • getDateInstance(): Return an instance of DateFormat for formatting times according to the user’s desired date format.

The DateFormat class provides several useful methods for displaying dates in different formats (e.g. MM/DD/YYYY or DD-MMM-YY). For example:

DateFormat df = DateFormat.getDateInstance();  // get default date format String str = df.format(gcal.getTime());  // format date according to default date format System.out.println(str); // prints out '03/22/2018' 

Examples of Java Gregorian Calendar Code

Now that you have seen how to create and manipulate Gregorian Calendar objects, let’s look at some examples of how to use them in Java applications. Here’s a simple program that prints out today’s date using a GregorianCalendar object:

public class Main {    public static void main(String[] args) {        // Create a new Gregorian calendar object, representing today's date         GregorianCalendar gcal = new GregorianCalendar();        // Print out today's date in mm/dd/yyyy format         DateFormat df = DateFormat.getDateInstance();          String str = df.format(gcal.getTime());          System.out.println("Today's date is: " + str);    } }/* Output: Today's date is: 03/22/2018 */ 

The following program demonstrates how you can create and manipulate a Gregorian Calendar object manually:

public class Main {    public static void main(String[] args) {        // Create a new Gregorian calendar object         GregorianCalendar gcal = new GregorianCalendar();        // Set the date to Feb 7th in 2019         gcal.set(2019, 1, 7);        // Print out today's date in mm/dd/yyyy format         DateFormat df = DateFormat.getDateInstance();          String str = df.format(gcal.getTime());          System.out.println("Today's date is: " + str);    } } /* Output: Today's date is: 02/07/2019 */ 

Conclusion

As you have seen, Java provides an easy-to-use class called the GregorianCalendar class, part of the java.util package, which allows developers to work with dates and times with ease. By utilizing this class, developers can create, access, manipulate and format dates in various formats to suit their needs.

Picture of Sarang Sharma

Sarang Sharma

Sarang Sharma is Software Engineer at Bito with a robust background in distributed systems, chatbots, large language models (LLMs), and SaaS technologies. With over six years of experience, Sarang has demonstrated expertise as a lead software engineer and backend engineer, primarily focusing on software infrastructure and design. Before joining Bito, he significantly contributed to Engati, where he played a pivotal role in enhancing and developing advanced software solutions. His career began with foundational experiences as an intern, including a notable project at the Indian Institute of Technology, Delhi, to develop an assistive website for the visually challenged.

Written by developers for developers

This article was handcrafted with by the Bito team.

Latest posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Top posts

Mastering Python’s writelines() Function for Efficient File Writing | A Comprehensive Guide

Understanding the Difference Between == and === in JavaScript – A Comprehensive Guide

Compare Two Strings in JavaScript: A Detailed Guide for Efficient String Comparison

Exploring the Distinctions: == vs equals() in Java Programming

Understanding Matplotlib Inline in Python: A Comprehensive Guide for Visualizations

Get Bito for IDE of your choice