Java Date and Time – GregorianCalendar Class with Example

Date and Time are the main factors used in every technology. Let’s connect the concept with an example, when we withdraw cash from ATM we will get a notification of withdrawal through a server that you withdraw an amount of XXXXXX on the date DD-MM-YYYY at time HH.MM.SS. This information will be stored in the database and used to sync your account information. This is the importance of date and time. Now let us see how you can implement it using Java.

We can change the format of Java Date and Time according to requirement. This feature is easy and simple to use.

Java date and time tutoria

1.  Java Date Class?

Java Date class is available in the java.util package which also encapsulates the current time and date.
It supports the two constructors, namely,

Date()This constructor initializes the current Java date and time.
Date(long millisec)It is used to count the number of milliseconds elapsed.

Master the Concept of Constructor in Java in One-Shot!

2. Java Date Class – Methods

MethodDescription
boolean after(Date date)It returns true when the invoked Date object is later than the specified date.
boolean before(Date date)It is the same as the above with the only difference that it is true when the date is earlier than the Date object.
Object clone( )It duplicates the invoked object.
int compareTo(Date date)It compares the value of the specified object to the invoking object, if it is equal then returns zero, if later then than positive and negative when it is earlier.
int compareTo(Object obj)It throws a ClassCastException if obj is not a Date class.
boolean equals(Object date)It is true only when the invoking Date object returns the same time and date, otherwise, it returns false.
long getTime( )It returns the number of milliseconds elapsed.
int hashCode( )For am invoking object, it returns a hash code.
void setTime(long time)It sets the date and time as specified by Time.
String toString( )Converts the Date object into a string.

Java Date and Time - Java Date Class

Recommended Reading – Java String with syntax & Example

2.1 How to get Current Java Date and Time?

To get current Java Date and Time, follow this java program.

package com.dataflair.datetime;
import java.util.Date;
public class CurrentDateAndTime {

  public static void main(String args[]) 
  {
    Date date = new Date();
    System.out.println(date.toString());
  }
}

Output-

Current Java Date and Time

2.2 Java Date Comparison

Following are the three approaches to look at two dates and compare them –

  • You can use getTime( ) to get the number of milliseconds that have passed since midnight, January 1, 1970, for the two questions and afterward think about these two esteems.
  • You can utilize the methods before( ), after( ), and equals to( ). Since the twelfth of the month precedes the eighteenth. For instance, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.
  • You can utilize the compareTo( ) strategy, which is characterized by the Comparable interface and actualized by Date.

Don’t forget to revise Interface in Java

2.3 Java Date Formatting Using SimpleDateFormat

SimpleDateFormat class mainly formats and parses the data. We can change the date from one format to another format. It interprets the string date format into a date object. Accordingly, we can modify the date.

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

Output-

Java Date Formatting Using SimpleDateFormat

Important Java Keywords that you must know

2.4 Simple DateFormat Format Codes

CharacterDescriptionExample
GEra designatorAD
yYear in four digits2001
MMonth in yearJuly or 07
dDay in month10
hHour in A.M./P.M. (1~12)12
HHour in day (0~23)22
mMinute in hour30
sSecond in minute55
SMillisecond234
EDay in weekTuesday
DDay in year360
FDay of week in month2 (second Wed. in July)
wWeek in year40
WWeek in month1
aA.M./P.M. markerPM
kHour in day (1~24)24
KHour in A.M./P.M. (0~11)10
zTime zoneEastern Standard Time
Escape for textDelimiter
Single quote`

2.5 Java Date Formatting Using printf

We can format the date and time very easily using the printf function. To do so we use a two-letter format, starting with t and ending in one of the letters.

Example –

package com.dataflair.datetime;
import java.util.Date;
public class DateFormattingusingPF {

  public static void main(String args[]) 
  {     
    Date date = new Date();
    String formatofDate = String.format("Current Date/Time : %tc", date );
    System.out.printf(formatofDate);

  }
}

Output-

Java Date Formatting Using printf

It would be somewhat senseless if you supply the date multiple times to format each part. For that, a format string can indicate the index of the argument to be formatted.

package com.dataflair.datetime;
import java.util.Date;
public class DateFormattingusingPF1 
{
  public static void main(String args[]) 
  {
    Date date = new Date(); 
    System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);
  }

}

Date-formatting-using-printf1

The index follows the % and it must be ended by a $.

Let’s learn the concept of Command-Line Argument

We can also use < flag in this. It indicates the same argument.

package com.dataflair.datetime;
import java.util.Date;
public class DateFormattingUsingPF2 {

  public static void main(String args[]) 
  {
    Date date = new Date();
    System.out.printf("%s %tB %<te, %<tY", "Due date:", date);
  }
}

Output-Date-formatting-using-printf2

2.6 Java Date and Time Conversion Characters

Here, is the list of characters and their descriptions for Java date and time conversion characters.

CharacterDescription
cComplete date and time
FISO 8601 date
DU.S. formatted date (month/day/year)
T24-hour time
r12-hour time
R24-hour time, no seconds
YFour-digit year (with leading zeroes)
yLast two digits of the year (with leading zeroes)
CFirst two digits of the year (with leading zeroes)
BFull month name
bAbbreviated month name
mTwo-digit month (with leading zeroes)
dTwo-digit day (with leading zeroes)
eTwo-digit day (without leading zeroes)
AFull weekday name
aAbbreviated weekday name
jThree-digit day of year (with leading zeroes)
HTwo-digit hour (with leading zeroes), between 00 and 23
kTwo-digit hour (without leading zeroes), between 0 and 23
ITwo-digit hour (with leading zeroes), between 01 and 12
lTwo-digit hour (without leading zeroes), between 1 and 12
MTwo-digit minutes (with leading zeroes)
STwo-digit seconds (with leading zeroes)
LThree-digit milliseconds (with leading zeroes)
NNine-digit nanoseconds (with leading zeroes)
PUppercase morning or afternoon marker
pLowercase morning or afternoon marker
zRFC 822 numeric offset from GMT
ZTime zone
sSeconds since 1970-01-01 00:00:00 GMT
QMilliseconds since 1970-01-01 00:00:00 GMT

Have you checked Character Class in Java with Real-time Example

2.7 Parsing Strings into Dates

If we want to convert a string to date we use the parse() method of DateFormat and SimpleDateFormat classes.

package com.dataflair.datetime;
import java.util.*;
import java.text.*; 
public class ParsingStringIntoDate {

  public static void main(String args[]) {
    SimpleDateFormat formatOfDate = new SimpleDateFormat ("yyyy-MM-dd");
    String input = args.length == 0 ? "1818-11-11" : args[0];
    System.out.print(input + " Parses as ");
    Date date;
    try 
    {
      date = formatOfDate.parse(input);
      System.out.println(date);
    }
    catch (ParseException e) 
    {
      System.out.println("Unparseable using " + formatOfDate);
    }
  }
}

Output-

Parsing-String-into-Date

Do you know about StringBuffer in Java (with its Constructors & Methods)?

2.8 Sleeping for a While

If we want to sleep the time for a while then we use thread.sleep() method

package com.dataflair.datetime;
import java.util.*;
public class SleepingForAWhile {

  public static void main(String args[]) 
  {
    try 
    {
      System.out.println(new Date( ) + "\n");
      Thread.sleep(5*60*10);
      System.out.println(new Date( ) + "\n");
    } 
    catch (Exception e) 
    {
      System.out.println("Got an exception!");
    }
  }
}

Output-Sleeping-for-a-while

2.9 Measuring Elapsed Time

To count time in milliseconds.

package com.dataflair.datetime;
import java.util.*;
public class MeasuringElapsedTime {

  public static void main(String args[]) 
  {
    try 
    {
      long start = System.currentTimeMillis( );
      System.out.println(new Date( ) + "\n");        
      Thread.sleep(5*60*10);
      System.out.println(new Date( ) + "\n");        
      long end = System.currentTimeMillis( );
      long difference = end - start;
      System.out.println("Difference is : " + difference);
    } 
    catch (Exception e) 
    {
      System.out.println("Got an exception!");
    }
  }
}

Output-Measuring-Elapsed-Time

Before we start the next topic you should know about the working of abstract class in Java

3. GregorianCalendar Class in Java

GregorianCalendar is a subclass that has the implementation of all the inherited members either from an interface or abstract class of a calendar that implements the most widely used Gregorian Calendar.

It implements Gregorian and Julian calendars. That is, dates are computed by assuming the current rules are frequently far backward and forward in time. As a result, it may be used for all years to produce constant results. Though, the dates received using GregorianCalendar are accurate only from March 1, 4 AD onward, when modern Julian calendar rules were approved. Before this date, leap year prototypes were applied unevenly, and before 45 BC the Julian calendar did not even exist.

There are  few constructors for GregorianCalendar objects −

  • GregorianCalendar()

It sets using the present time in the default time zone with the default area for the Gregorian Calendar.

  • GregorianCalendar(int year, int month, int date)

Develops a GregorianCalendar with the given date set in the default time zone with the default area.

  • GregorianCalendar(int year, int month, int date, int hour, int minute)

Develops a GregorianCalendar for a default time zone for default area with a given time and date set.

  • GregorianCalendar(int year, int month, int date, int hour, int minute, int second)

It builds a GregorianCalendar for a default time zone and given time and date.

  • GregorianCalendar(Locale aLocale)

Builds a GregorianCalendar in light of the present time in the default time zone with the given area.

  • GregorianCalendar(TimeZone zone)

Builds a GregorianCalendar using default zone and its default time.

  • GregorianCalendar(TimeZone zone, Locale aLocale)

It builds a GregorianCalendar with the given present time and zone for the given location. Here is the rundown of a couple of helpful help techniques gave by GregorianCalendar class.

You Can’t Afford to Miss Out the Concept of Inheritance in Java 

  • void add(int field, int sum)

Includes the predetermined (marked) measure of time to the given time field, in light of the logbook’s standards.

  • ensured void computeFields()

Believers UTC as milliseconds to time handle esteems.

  • protected void computeTime()

Overrides Calendar Converts time field into UTC (milliseconds).

  • boolean equals(Object obj)

Thinks about this GregorianCalendar to a question reference.

  • int get(int field)

Gets the incentive for a given time field.

  • int getActualMaximum(int field)

Returns the greatest esteem that this field could have, given the present date.

  • int getActualMinimum(int field)

Returns the base esteem that this field could have, given the present date.

  • int getGreatestMinimum(int field)

Returns most noteworthy least incentive for the given field if fluctuates.

  • Date getGregorianChange()

Gets the Gregorian Calendar change date.

  • int getLeastMaximum(int field)

Returns least most extreme incentive for the given field if shifts.

  • int getMaximum(int field)

Returns most extreme incentive for the given field.

  • Date getTime()

Gets this current Calendar’s present time.

  • long getTimeInMillis()

Gets this present Calendar’s present time as a long.

  • TimeZone getTimeZone()

Gets the time z atone.

  • int getMinimum(int field)

Returns least an incentive for the given field.

  • int hashCode()

Overrides hashCode.

Also, see Method Overriding in Java with Rules and Real-time Examples

  • boolean isLeapYear(int year)

Decides whether the given year is a leap year.

  • void roll(int field, boolean up)

Includes or subtracts (up/down) a solitary unit of time on the given time field without changing bigger fields.

  • void set(int field, int esteem)

Sets the time field with the given field.

  • void set(int year, int month, int date)

Sets the qualities for the fields year, month, and date.

  • void set(int year, int month, int date, int hour, int minute)

Sets the qualities for the fields year, month, date, hour, and moment.

  • void set(int year, int month, int date, int hour, int minute, int second)

This sets the qualities for fields’ year, month, date, hour, moment, and second for the GregorianCalender.

  • void setGregorianChange(Date date)

Sets the GregorianCalendar change date.

  • void setTime(Date date)

Sets this present Calendar’s present time with the given Date.

  • void setTimeInMillis(long millis)

Sets this present Calendar’s present time from the given long field.

  • void setTimeZone(TimeZone esteem)

Sets the time zone with the given time zone field.

  • String toString()

Returns a string replica of this date-book.

Example –

package com.dataflair.datetime;
import java.util.*;
public class GregorianCalendarClass 
{
  public static void main(String args[])
  {
    String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
        "Oct", "Nov", "Dec"};
    int year;
    GregorianCalendar gcalendar = new GregorianCalendar();
    System.out.print("Date: ");
    System.out.print(months[gcalendar.get(Calendar.MONTH)]);
    System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
    System.out.println(year = gcalendar.get(Calendar.YEAR));
    System.out.print("Time: ");
    System.out.print(gcalendar.get(Calendar.HOUR) + ":");
    System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
    System.out.println(gcalendar.get(Calendar.SECOND));
    if(gcalendar.isLeapYear(year))
    {
      System.out.println(" current year is a leap year");
    }
    else 
    {
      System.out.println("current year is not a leap year");
    }
  }
}

Output-

Gregorian-Calendar-Class

Confused, What to do next? It’s time to explore Java Comparator Interface

Java Quiz

4. Summary

In this Java Date and Time tutorial, we learned about the Java Date class available in java.util and GregorianCalendar Class in Java. Moreover, we discussed how to measure elapsed time in Java, how to parsing a string into dates, and how to get current Date and time in Java. In Conclusion, we saw Sleeping for a While, Java Date, and Time Conversion Characters, Java Date Formatting Using printf, Simple DateFormat Format Codes, Java Date Formatting Using SimpleDateFormat, and Java Date Comparison.

Furthermore, if you have any queries, feel free to ask in a comment section.

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.