Site icon DataFlair

Java Date and Time – GregorianCalendar Class with Example

java date and time

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 Name Description 
1 boolean 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.
2 boolean 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.
3 Object clone() This method clones the Date object that calls it.
4 int 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.
5 int 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).
6 boolean 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.
7 long getTime() This method returns the number of milliseconds that have passed since January 1, 1970. 
8 int hashCode() This method creates a hash code and returns it for the object that calls it.
9 void 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.
10 String 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:

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.

Character Meaning Example
G Era designator AD, BC
y Year in digits 2021
M Month in Year August or 08
d Day in Month 19
h Hour in A.M./P.M.(12-hour clock) 10
H Hour in day(24 hour clock[0-23]) 13
m Minute in hour 05
s Second in minute 57
S Millisecond 100
E Day in Week Thursday
D Day in year 225
F Day of week in the month 3(Third Wednesday in August)
w Week in year 35
W Week in month 3
a A.M./P.M. marker P.M.
k Hour in day(1-24) 24
K Hour in A.M./P.M.(0-11) 0
z Time Zone Indian Standard Time
Escape for text Delimiter
Single Quote

Characters to convert java Date and Time:

Character Meaning Example
c Complete date and time Thu August 19 13:50:45 IST 2021
F ISO 8601 date format 2021-08-19
D United States formatted date (month/day/year) 08/19/2021
T 24- hour time 13:50:45
r 12-hour time 01:50:45 pm
R 24 hour time without seconds 13:45
Y Four-digit year 2021
y Last two digits of the year 21
C First two digits of the year 20
B Full name of the month August
b Abbreviation of the month name Aug
m Two-digit month number 08
d Two-digit day of the month(With leading Zero) 19
e Two-digit day of the month(Without leading zero) 9
A Full form of the day name Thursday
a Abbreviated form of the day name Thu
j Three-digit day of the year with leading zero 015
H Two-digit hour with leading zero(00-23) 14
k Two-digit hour without leading zero(0-23) 14
I Two-digit hour with leading zeros (01-12) 02
l Two-digit hour without leading zeros (1-12) 2
M Two-digit minutes with leading zeroes 03
S Two-digit seconds with leading zeroes 07
L Three-digit milliseconds with leading zeroes 077
N Nine-digit nanoseconds with leading zeroes 000002234
P Uppercase AM or PM PM
p Lowercase am or pm pm
z RFC 822 numeric offset from GMT +0530
Z Time Zone  IST
s Seconds since 1970-01-01 00:00:00 GMT 1629362389
Q Milliseconds since 1970-01-01 00:00:00 GMT 1629362311015

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

Exit mobile version