Java Date and Time – Java Date Class & GregorianCalendar Class

1. Java Date and Time – Objective

In this Java Date and Time tutorial we are going to learn What is Java Date Class and Methods of Java Date Class. Moreover, we will discuss GregorianCalendar Class in Java Programming Language and how to get the current date and time in java. At last, we will discuss examples of Java Date and time i.e. java.util.
So, let us start Java Date and Time.

Java Date and Time - Java Date Class

Java Date and Time – Java Date Class & GregorianCalendar Class

2.  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.

Do you know What is Java String, Methods, and Constructor?

3. Java Date Class – Methods

MethodDescription
boolean after(Date date)It returns true when true when the invoked Date object is later than specified date.
boolean before(Date date)It is 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 string.
Java Date and Time - Java Date Class

Java Date and Time – Java Date Class & GregorianCalendar Class

a. How to get Current Java Date and Time

To Get Current Java Date and Time, follow this java program.

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

Read about Types of Inner Classes in Java

b. Java Date Comparison

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

  • You can utilize getTime( ) to acquire 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 strategies 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.

c. Java Date Formatting Using SimpleDateFormat

SimpleDateFormat is a solid class for arranging and parsing dates in an area delicate way. SimpleDateFormat enables you to begin by picking any client characterized designs for date-time arranging.

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

Let’s Discuss Method Overloading vs Overriding in Java

d. 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`

Read about Multithreading in Java Programming Language 

e. Java Date Formatting Using printf

Java Date and time designing should be possible effortlessly utilizing printf technique. You utilize a two-letter organize, beginning with t and completion in one of the letters of the table as appeared in the accompanying code.
Example –

import java.util.Date;
public class DateDemo {
   public static void main(String args[]) {     
      Date date = new Date();
      String str = String.format("Current Date/Time : %tc", date );
      System.out.printf(str);
   }
}

It would be somewhat senseless in the event that you needed to supply the date numerous circumstances to arrange each part. Therefore, an organization string can show the list of the contention to be arranged.

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

The list should quickly take after the % and it must be ended by a $.
We can also use < flag in this.

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

Let’s at Difference Between Checked and Unchecked Exceptions in Java

f. Java Date and Time Conversion Characters

Here, is the list of character 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

g. Parsing Strings into Dates

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

Do you know Java Extends vs Implements With Example Program

h. Sleeping for a While

import java.util.*;
public class SleepDemo {
   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!");
      }
   }
}

i. Measuring Elapsed Time

To count time in milliseconds.

import java.util.*;
public class DiffDemo {
   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 diff = end - start;
         System.out.println("Difference is : " + diff);
      } catch (Exception e) {
         System.out.println("Got an exception!");
      }
   }
}

Read interesting Topic – How to Convert Colored Image in Java

Java Quiz

4. GregorianCalendar Class in Java

GregorianCalendar is a solid execution of a Calendar class that actualizes the typical Gregorian date-book with which you are commonplace. We didn’t talk about Calendar class in this instructional exercise, you can look into standard Java documentation for this.
The getInstance( ) strategy for Calendar restores a GregorianCalendar instated with the present Java date and time in the default area and time zone. GregorianCalendar characterizes two fields: AD and BC. These speak to the two times characterized by the Gregorian schedule.
There are additionally a 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.
Read about Types of Annotations in Java Programming Language

  • 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 couple of helpful help techniques gave by GregorianCalendar class −

  • 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).
Do You Know How to Establish Java Socket Connection

  • 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.
Let’s Know about Pair Class in Java With Techniques

  • 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.

  • 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.
Let’s Explore Java Exception – Types & Java Catch Exceptions

  • 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 portrayal of this date-book.
Example –

import java.util.*;
public class GregorianCalendarDemo {
   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");
      }
   }
}

This was all about Java Date and Time Tutorial. Hope you like our explanation.

5. Conclusion

In this Java Date and Time tutorial, we learned about 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 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 query, feel free to ask in a comment section.

Related Topic- Java Comparator Interface 

For reference

Leave a Reply

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