Java Date and Time – GregorianCalendar Class with Example

Free Java courses with 37 real-time projects - Learn Java

The definition of an efficient programming language depends on how well it can handle Date and Time. Java provides us with inbuilt classes like Date and Calendar to handle operations related to date and time. In this article, we will discuss at length how these classes and their methods can be implemented into a java program.

The Date class in Java:

The java.util package in Java contains many utilities that are very important for a program. One such class is the Date class. This class deals with operations related to date and time. This class implements Cloneable, Serializable and comparable interfaces of java.

Java Date class constructors:

The Date class consists of six java constructors, but only two of them are in use, the other four are deprecated.

1. Date()

This is the default constructor of the Date class. It is used to initialize the Date class objects with the present date and time.

2. Date(long millisecond)

It is a parameterized constructor of the Date class. The argument passed is in the form of milliseconds. It initializes the object with the total milliseconds that passes since midnight, January 1, 1970.

Java Date class Methods:

SL. No. Method NameDescription 
1boolean after(Date date)This method returns true if the called Date object contains a date that is later than the one passed through the parameter. Otherwise, it returns false.
2boolean before(Date date)This method returns true if the called Date object contains a date that is earlier than the one passed through the parameter. Otherwise, it returns false.
3Object clone()This method clones the Date object that calls it.
4int compareTo(Date date)This method is used to compare the called object’s date to the date passed through the parameter. It returns 0 if the dates are equal. It returns a negative value if the object’s date is earlier and positive value if the object’s date is later.
5int compareTo(Object obj)This method works in the same way as the compareTo(Date date) method if the Object obj is an object of Date class, else it throws an exception(ClassCastException).
6boolean equals(Object date)This method performs an equality check. It returns true if the object’s date is the same as the date passes through the parameter. Else it returns false.
7long getTime()This method returns the number of milliseconds that have passed since January 1, 1970. 
8int hashCode()This method creates a hash code and returns it for the object that calls it.
9void setTime(long time)This method sets the time to the time passed through the parameter and represents it in milliseconds of time that elapsed since January 1, 1970.
10String toString()This method changes the date to string and returns it. 

Getting Current Date and time:

We will use two techniques to get the current date and time of our system.
1. Using the Date class
2. Using the Calendar class

1. Using Date class in Java:

In this method, we will create an object of the Date class and then call the toString() method using the object to get the present date and time of the system.

Code to get current date and time using Date Class:

package com.DataFlair.DateAndTime;
import java.util.Date;
public class CurrDateUsingDateClass
{
      public static void main(String args[]) {
      Date date = new Date();
      System.out.println(date.toString());
   }
}

The output of the above code:

Thu Aug 19 11:16:20 IST 2021

2. Using Calendar Class:

We will use the getInstance() method of the Calendar class to create an instance, and use it to call the getTime() method to get the current time of the system.

Code to get current date and time using Calendar Class:

package com.DataFlair.DateAndTime;
import java.util.Calendar;
public class CurrDateUsingCalenderClass
{
    public static void main(String args[]) 
    {
        Calendar current = Calendar.getInstance();
        System.out.println(current.getTime());
    }
}

The output of the above code is:

Thu Aug 19 11:21:52 IST 2021

Comparison of Date

We can compare two dates in three ways:

  • Using the getTime() function to get the number of milliseconds since January 1, 1970, for both the dates and then compare the two values.
  • Using the before(), after(), and equals(), methods to compare the boolean values returned by the methods.
  • There is also the compareTo() method, which can be used to compare two dates. It returns 0, negative and positive values, depending on the dates compared.

Formatting Date Using SimpleDateFormat class:

We can format dates using the concrete class called SimpleDateFormat. We can start by choosing any user-defined pattern for date formatting.

Code to understand the use of SimpleDateFormat:

package com.DataFlair.DateAndTime;
import java.util.*;
import java.text.*;
public class DateFormatting
{
    public static void main(String args[]) 
   {
      Date CurrDate = new Date( );
      SimpleDateFormat formatDate = new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
      System.out.println("Current Date(Formatted): " + formatDate.format(CurrDate));
   }
}

The output of the above code:

Current Date(Formatted): Thu 2021.08.19 at 11:58:26 AM IST

SimpleDateFormat formatting codes:

In the above program, we used codes like E, yyyy, etc. These codes are all specific pattern codes defined inside the SimpleDateFormat. Let us discuss all the codes through the table below.

CharacterMeaningExample
GEra designatorAD, BC
yYear in digits2021
MMonth in YearAugust or 08
dDay in Month19
hHour in A.M./P.M.(12-hour clock)10
HHour in day(24 hour clock[0-23])13
mMinute in hour05
sSecond in minute57
SMillisecond100
EDay in WeekThursday
DDay in year225
FDay of week in the month3(Third Wednesday in August)
wWeek in year35
WWeek in month3
aA.M./P.M. markerP.M.
kHour in day(1-24)24
KHour in A.M./P.M.(0-11)0
zTime ZoneIndian Standard Time
Escape for textDelimiter
Single Quote

Characters to convert java Date and Time:

CharacterMeaningExample
cComplete date and timeThu August 19 13:50:45 IST 2021
FISO 8601 date format2021-08-19
DUnited States formatted date (month/day/year)08/19/2021
T24- hour time13:50:45
r12-hour time01:50:45 pm
R24 hour time without seconds13:45
YFour-digit year2021
yLast two digits of the year21
CFirst two digits of the year20
BFull name of the monthAugust
bAbbreviation of the month nameAug
mTwo-digit month number08
dTwo-digit day of the month(With leading Zero)19
eTwo-digit day of the month(Without leading zero)9
AFull form of the day nameThursday
aAbbreviated form of the day nameThu
jThree-digit day of the year with leading zero015
HTwo-digit hour with leading zero(00-23)14
kTwo-digit hour without leading zero(0-23)14
ITwo-digit hour with leading zeros (01-12)02
lTwo-digit hour without leading zeros (1-12)2
MTwo-digit minutes with leading zeroes03
STwo-digit seconds with leading zeroes07
LThree-digit milliseconds with leading zeroes077
NNine-digit nanoseconds with leading zeroes000002234
PUppercase AM or PMPM
pLowercase am or pmpm
zRFC 822 numeric offset from GMT+0530
ZTime Zone IST
sSeconds since 1970-01-01 00:00:00 GMT1629362389
QMilliseconds since 1970-01-01 00:00:00 GMT1629362311015

Date formatting Using printf:

The above characters can be used easily to format date using the printf method. We just have to give a two-letter format starting with t and any of the above characters.

Code to understand the implementation of printf:

package com.DataFlair.DateAndTime;
import java.util.Date;
public class DateFormattingusingPrintf
{
    public static void main(String args[]) 
    {
      Date date = new Date();
      String str = String.format("Current Date/Time of the system : %tc", date );
      System.out.printf(str);
   }
}

The output of the above code:

Current Date/Time of the system : Thu Aug 19 14:13:20 IST 2021

We can apply multiple formatting at the same time as well. We just have to give % before every character and terminate with $

Code to implement multiple formatting using printf:

package com.DataFlair.DateAndTime;
import java.util.Date;
public class DateFormattingusingPrintf
{
    public static void main(String args[]) 
    {
      Date date_of_system = new Date();
      System.out.printf("%1$s %2$tB %2$td, %2$tY", "Current date of the system:", date_of_system);
   }
}

The output of the above code:

Current date of the system: August 19, 2021

We can also use < flag to indicate that the same argument as the preceding should be used again.

Code to understand flag in printf:

package com.DataFlair.DateAndTime;
import java.util.Date;
public class DateFormattingusingPrintf
{
    public static void main(String args[]) 
    {
      Date date = new Date();
      System.out.printf("%s %tB %<te, %<tY", "Current date of the system:", date);
   }
}

The output of the above code:

Current date of the system: August 19, 2021

Parsing strings into dates:

The SimpleDateFormat has a method called parse() which tries to parse a string according to the format stored in the given SimpleDateFormat object.

Code to understand the parse method:

package com.DataFlair.DateAndTime;
import java.util.*;
import java.text.*;
public class parseDate
{
     public static void main(String args[]) {
      SimpleDateFormat formatofDate = new SimpleDateFormat ("yyyy-MM-dd"); 
      String input = args.length == 0 ? "2021-08-19" : args[0]; 
      System.out.print(input + " is Parsed as "); 
      Date t;
      try {
         t = formatofDate.parse(input); 
         System.out.println(t); 
      } catch (ParseException e) { 
         System.out.println("The string is unparseable " + formatofDate); 
      }
   }
}

The output of the above code:

2021-08-19 is Parsed as Thu Aug 19 00:00:00 IST 2021

Making the program sleep for a while:

We can make a program sleep for any period of time from one millisecond up to a lifetime of our computer.

Code to make our system sleep for 6 seconds:

package com.DataFlair.DateAndTime;
import java.util.*;
public class Sleeping
{
   public static void main(String args[]) {
      try { 
         System.out.println(new Date( ) + "\n"); 
         Thread.sleep(10*60*10); 
         System.out.println(new Date( ) + "\n"); 
      } catch (Exception e) {
         System.out.println("Got an exception!"); 
      }
   }
}

The output of the above code:

Thu Aug 19 14:35:45 IST 2021

Thu Aug 19 14:35:51 IST 2021

Now let us try to calculate the time for which our program slept.

Code to calculate the time for which our program sleeps:

package com.DataFlair.DateAndTime;
import java.util.*;
public class Sleeping
{
     public static void main(String args[]) {
      try {
         long start = System.currentTimeMillis( );
         System.out.println(new Date( ) + "\n");
         Thread.sleep(10*60*10);
         System.out.println(new Date( ) + "\n");
         long end = System.currentTimeMillis( );
         long diff = end - start;
         System.out.println("Difference is : " + diff);
      } catch (Exception e) {
         System.out.println("Got an exception!");
      }
   }
}

The output of the above code:

Thu Aug 19 14:38:29 IST 2021

Thu Aug 19 14:38:35 IST 2021

Difference is : 6002

GregorianCalendar Class:

Another concrete implementation of the calendar class is the GregorianCalendar class. It implements the normal Gregorian Calendar. We can instantiate the GregorianCalendar class using the getInstance() method. It can define two fields: AD(Anno Domini)and BC(Before Christ).

There are several constructors in the GregorianCalendar class:
1. GregorianCalendar(): It is the default constructor of the GregorianCalendar class. The default constructor constructs a default calendar using the current time in the default time zone with the default location.

2. GregorianCalendar(int year, int month, int date): It is a parameterized constructor of the GregorianCalendar class that constructs a GregorianCalendar with the mentioned date in the default time zone with the default location.

3. GregorianCalendar(int year, int month, int date, int hour, int minute): It is a parameterized constructor of the GregorianCalendar class that constructs a GregorianCalendar with the mentioned date and time in the default time zone with the default location.

4. GregorianCalendar(int year, int month, int date, int hour, int minute, int second): It is a parameterized constructor of the GregorianCalendar class that constructs a GregorianCalendar with the given date and time in the default time zone with the default location.

5. GregorianCalendar(Locale location): It is a parameterized constructor of the GregorianCalendar class that constructs a GregorianCalendar based on the current time in the default time zone with the given location.

6. GregorianCalendar(TimeZone zone): It is a parameterized constructor of the GregorianCalendar class that constructs a GregorianCalendar based on the current time in the given time zone with the default location.

7. GregorianCalendar(TimeZone zone, Locale location): It is a parameterized constructor of the GregorianCalendar class that constructs a GregorianCalendar based on the current time in the given time zone with the given location.

GregorianCalendar Methods:

SL. No.SyntaxDescription
1void add(int field, int amount)This method adds the given amount of time to the specified field, depending on calendar rules.
2protected void computeFields()Using this method we can convert UTC as milliseconds to time field values.
3protected void computeTime()Using this method we can override Calendar Converts time field values to UTC as milliseconds.
4boolean equals(Object obj)Using this method we can compare the GregorianCalendar to an object reference.
5int get(int field)Using this method we can get the value for a given time field.
6int getActualMaximum(int field)Using this method we can get the maximum value that this field could have, given the current date.
7int getGreatestMinimum(int field)Using this method we can get the highest minimum value for the given field if varies.
8int getActualMinimum(int field)Using this method we can get the minimum value that this field could have, given the current date.
9Date getGregorianChange()Using this method we can get the Gregorian Calendar change date.
10int getLeastMaximum(int field)Using this method we can get the lowest maximum value for the given field if varies
11int getMaximum(int field)Using this method we can get the maximum value for the given field.
12Date getTime()This method gets this Calendar’s current time.
13long getTimeInMillis()Using this method we can get this Calendar’s current time as a long variable.
14TimeZone getTimeZone()This method gets the time zone.
15int getMinimum(int field)Using this method we can get the minimum value for the given field.
16int hashCode()This method Overrides the hashCode
17boolean isLeapYear(int year)This method helps us determine if the given year is a leap year.
18void roll(int field, boolean up)Using this method we can add or subtract (up/down) a single unit of time on the given time field without changing larger fields.
19void set(int field, int value)Using this method we can set the time field with the given value.
20void set(int year, int month, int date)Using this method we can Set the values for the fields year, month, and date.
21void set(int year, int month, int date, int hour, int minute)Using this method we can set the values for the fields year, month, date, hour, and minute.
22void set(int year, int month, int date, int hour, int minute, int second)Using this method we can set the values for the fields year, month, date, hour, minute, and second.
23Void setGregorianChange(Date date)This method sets the GregorianCalendar change date.
24void setTime(Date date)Using this method we can set the Calendar’s current time with the given Date.
25Void setTimeInMillis(long millis)Using this method we can set the Calendar’s current time from the given long value.
26void setTimeZone(TimeZone value)Using this method we can set the time zone with the given time zone value.
27String toString()This method can return a string representation of the calendar.

Code to understand the implementation of GregorianCalendar:

package com.DataFlair.DateAndTime;
import java.util.*;
public class GregoriancalendarImplementation
{
    public static void main(String args[]) {
      String Month[] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", 
         "October", "November", "December"};
      int year;
      GregorianCalendar calendar = new GregorianCalendar();
      System.out.print("Date: ");
      System.out.print(Month[calendar.get(Calendar.MONTH)]);
      System.out.print(" " + calendar.get(Calendar.DATE) + " ");
      System.out.println(year = calendar.get(Calendar.YEAR));
      System.out.print("Time: ");
      System.out.print(calendar.get(Calendar.HOUR) + ":");
      System.out.print(calendar.get(Calendar.MINUTE) + ":");
      System.out.println(calendar.get(Calendar.SECOND));
      if(calendar.isLeapYear(year)) {
         System.out.println("The current year is a leap year");
      }else {
         System.out.println("The current year is not a leap year");
      }
   }
}

The output of the above code:

Date: August 19 2021
Time: 3:53:13
The current year is not a leap year

Conclusion:

In this article, we saw how java can be used to handle various operations using date and time. This is a very important concept, as many software requires proper handling of date and time to be implemented smoothly.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *