What Is Data and Time Function in Java?

Introduction  

Technology is always evolving, as are the programming languages used to develop it. The Java programming language is one of the most widely employed languages in the software world. The programming language is used in practically every sector, including application or web development, Big Data, Machine Learning, Artificial Intelligence, mobile development, and so on. 

An optimal programming language is defined by how effectively it handles Date and Time. Java has classes such as Date and Calendar to manage the Date class in Java and time operations. This guide will go through how to integrate these classes and methods in a Java application. 

What Is Date Class in Java?  

In Java, the java.util package includes several utilities that are essential for a program. The date class in Java is one such utility. This class is associated with date and time operations. This class implements the Java Cloneable, Serializable, and similar interfaces. 

Java Date class constructors: 

The Date class has six Java constructors, but only two are used; the other four are obsolete. 

1. Date() 

The Date class is a default constructor. It is used to set the date and time on the date class in Java objects. 

2. Date(long millisecond) 

It is a parameterized Date class constructor. The argument passed is in the constitution of milliseconds. It initiates the object with the total milliseconds from midnight of Jan 1, 1970. 

Date Constructors in Java Example: 

// Java application showing Date constructors  

  • import java.util.*; 
  • public class Main 
  • { 
  •     public static void main(String[] args) 
  •     { 
  •         Date da1 = new Date(); 
  •         System.out.println(“The present java new date is ” da1); 
  •         Date da2 = new Date(2323223232L); 
  •         System.out.println(“The date displayed is ” da2 ); 
  •     } 
  • } 

Output: 

The present java new date is Fri Dec 12 18:35:37 IST 2022 

The date displayed is Wed Jan 28 02:50:23 IST 1970 

Methods Of Date Class

Tabled below is the list of methods of Date class in Java: 

Method Name  Description 
boolean after(Datedate)  The method gives true if the called date object in Java includes a date that is later than the one specified by the argument. Otherwise, it returns false. 
boolean before(Datedate)  The method gives true if the called Date object includes a date that is earlier than the one specified by the argument. Otherwise, it returns false. 
Object clone()  The method duplicates the date object in Java that requests it. 
int compareTo(Date date)  The method compares the requested object’s date to the date given by the argument. If the dates are the same, it gives 0. It gives a negative number if the object’s date is before and a positive value if the object’s date is after. 
int compareTo(Object 

obj) 

If the Object obj is a Date class object, this function behaves similarly to the compareTo(Date date) method; otherwise, it throws an error (ClassCastException). 
boolean equals(Object date)  The method checks for equality. It returns true if the object’s date and the date sent by the argument are the same. Otherwise, it returns false. 
long getTime()  The method returns the actual sum of milliseconds since January 1, 1980. 
int hashCode()  The method generates a hash code and returns it to the calling object. 
void setTime(long time)  The method changes the time to the time specified by the argument and displays it in milliseconds from January 1, 1970. 
String toString()  The date is converted to a string and returned by this method. 

Date Class in Java Example: 

  • // Java application showing methods of the Date class 
  • import java.util.*; 
  • public class Main 
  • { 
  •     public static void main(String[] args) 
  •     { 
  •         // Create a date 
  •         Date nda1 = new Date(2000, 11, 21); 
  •         Date nda2 = new Date(); 
  •         Date nda3 = new Date(2010, 1, 3); 
  •         boolean ab = neda3.after(da1); 
  •         System.out.println(“The date neda3 comes later than ”  
  •                            “the date neda2: ” ab); 
  •         boolean ba = ned3.before(d2); 
  •         System.out.println(“the date neda3 comes prior to ”  
  •                            “date neda2: ” ba); 
  •         int ca = neda1.compareTo(nda2); 
  •         System.out.println(ca); 
  •         System.out.println(“Milliseconds since Jan 1 ”  
  •                 “1980 to date neda1 is ” neda1.getTime()); 
  •         System.out.println(“Prior change ” neda2); 
  •         neda2.setTime(204587433443L); 
  •         System.out.println(“After change ” neda2); 
  •     } 
  • } 

Output: 

The date neda3 comes later than date neda2: true 

The date neda3 comes prior to date neda2: false 

Milliseconds since Jan 1, 1980, to date neda1 is 60935500800000 

Prior change Tue Jul 12 13:13:16 UTC 2016 

After change Fri Jun 25 21:50:33 UTC 1976 

Getting the Current Date And time  

To obtain our system’s current date in Java and time, we will employ two methods. 

  1. Making use of Date class
  2. Making use of Calendar class
  1. Using Date Class: 

In this method, we will build a date class in Java object and then use it to use the function toString() method to acquire the system’s current Java DateTime. 

Date Class code to retrieve the current date and time: 

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

The output of the date class code: 

Fri Dec 2 11:16:20 IST 2022 

  1. Using Calendar Class: 

We’ll use the Calendar class’s getInstance() function to create an instance, then use it to execute the getTime() method to have the system’s current time. 

Code to retrieve the current date and time using Calendar Class: 

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

The output of the above code is: 

Fri Dec 2 11:21:52 IST 2022 

Comparing Dates  

Dates can be compared in three ways: 

  • Using the getTime() method, calculate the number of milliseconds from January 1, 1970, and compare the two numbers. 
  • To compare the boolean values returned by the methods, use the before(), after(), and equals() methods. 
  • There’s also the compareTo() date function in Java, which compares two dates. Depending on the dates compared, it gives zero, negative, or positive values. 

Date Formatting  

Let’s go through the different methods of Date formatting: 

Using SimpleDateFormat Class: 

The format string in the SimpleDateFormat object’s argument should include the structure in which the date string should be processed. This table contains the String’s syntax. We utilize the letters in the table below to define our pattern string. 

Letter  Represent  Type  Example 
G  Era designation  Text  AD 
y  Year  Year  2021 or 21 
M  Month of year  Month  March; Mar; 03 
w  Week number of Year  Number  12 
W  Week number of Month  Number  3 
D  Day of year  Number  074 
d  Day of month  Number  15 
E  Name of the Day  Text  Monday; Mon 
a  AM/PM  Text  PM 
H  Hrs of the day (0-23)  Number  19 
k  Hrs of the day (1-24)  Number  20 
K  Hrs in AM/PM (0-11)  Number  07 
h  Hrs in AM/PM (1-12)  Number  08 
m  Minutes  Number  37 
s  Seconds  Number  45 
S  Milliseconds  Number  456 
z  Time zone  General time zone  Indian Standard Time or IST or GMT 05.30 
Z  Time zone  RFC 822-time zone  0530 
X  Time zone  ISO 8601-time zone  0530; 05:30 

Code to comprehend the usage of SimpleDateFormat: 

  • package com.UNext.DateAndTime; 
  • import java.util.*; 
  • import java.text.*; 
  • public class DateFormatting 
  • { 
  •  public static void main(String args[])  
  •  { 
  •  Date PresDate = new Date( ); 
  •  SimpleDateFormat formatDate1 = new SimpleDateFormat (“E yyyy.MM.dd ‘at’ hh:mm: ss a zzz”); 
  •  System.out.println(“Present java new date (Formatted): ” formatDate.format(PresDate)); 
  •  } 
  • } 

Output of the code: 

Present java new date (Formatted): Friday 2022.12.02 at 11:58:26 AM IST 

Formatting Using printf: 

Code to comprehend the execution of printf: 

  • package com.UNext.DateAndTime; 
  • import java.util.Date; 
  • public class DateFormatwithPrintf 
  • { 
  •  public static void main(String args[])  
  •  { 
  •  Date date = new Date(); 
  •  String strin = String.format(“Time in the system : %tc”, date ); 
  •  System.out.printf(strin); 
  •  } 
  • } 

Output of the code: 

Time in the system: Fri Dec 02 14:13:20 IST 2022 

Parsing Strings into Dates: 

The SimpleDateFormat interface includes a method named parse() that aims to parse a string using the format provided in the SimpleDateFormat object. 

Code to comprehend the parse method: 

  • package com.UNext.DateAndTime; 
  • import java.util.*; 
  • import java.text.*; 
  • public class parDate 
  • { 
  •  public static void main(String args[]) { 
  •  SimpleDateFormat formatofDate = new SimpleDateFormat (“yyyy-MM-dd”);  
  •  String input = args.length == 0 ? “2022-12-02” : args[0];  
  •  System.out.print(input ” is presented as “);  
  •  Date M; 
  •  try { 
  •  M = formatofDate.parse(input);  
  •  System.out.println(M);  
  •  } catch (ParseException e) {  
  •  System.out.println(“The string cannot be parsed” formatofDate);  
  •  } 
  •  } 
  • } 

Output of the code: 

2022-12-02 is presented as Friday, Dec 02 00:00:00 IST 2022 

GregorianCalendar Class  

GregorianCalendar is a concrete execution of the Calendar class that enforces the standard Gregorian calendar.  

Calendar’s getInstance() date function in Java returns a GregorianCalendar with the current date and time in the default locale and time zone. The Gregorian calendar has two fields: AD Anno Domini and BC Before Christ. These are the two epochs as recognized by the Gregorian calendar. 

There are also various constructors for GregorianCalendar objects:

  1. GregorianCalendar():

This is the default constructor of the GregorianCalendar class. The constructor creates a calendar using the current time in the default time zone with the default location. 

  1. GregorianCalendar(int yr, int mon, int date):

This is a parametric constructor that constructs a GregorianCalendar with the mentioned date in Java in the standard time zone with the standard location. 

  1. GregorianCalendar(int yr, int mon, int date, int hr, int min):

This is a parametric constructor that creates a calendar with the cited date and time with the default location. 

  1. GregorianCalendar(int yr, int mon, int date, int hr, int min, int sec):

This is a parametric constructor that creates a calendar with the assigned Java datetime with the default location. 

  1. GregorianCalendar(Locale location):

This is a parametric constructor that creates a calendar depending on the present time in the default time zone with the assigned location. 

  1. GregorianCalendar(TimeZone zone):

This is a parametric constructor that creates a calendar depending on the present time in the assigned time zone with the default location. 

  1. GregorianCalendar(TimeZone zone, Locale location):

This is a parametric constructor that constructs a calendar based on the current time in the given time zone with the given location. 

GregorianCalendar Methods 

Some key methods for GregorianCalendar are listed below: 

  • According to the Calendar’s rules, add(…) will add or delete the provided amount of time from the given Calendar field. 
  • To determine whether the Calendar reflects a time before or after the time indicated by the given Object, use the operators after(…) and before(…) 
  • the Calendar’s specific value (or all of them) undefined, and to determine whether the specified calendar field already has a value set. 
  • In order to convert between Calendar and Date, use getTime() and setTime(…) 
  • To obtain or modify the time in milliseconds for the Calendar, use getTimeInMillis() and setTimeInMillis(…) 
  • A Calendar object’s time zone can be obtained or changed using the methods getTimeZone() and setTimeZone(…) 
  • To verify or set the Calendar’s leniency to tolerate erroneous numbers, use the functions isLenient() and setLenient(…) 
  • roll(…) to add or delete specified calendar field, alternative approach to change. 

Conclusion 

In this Java Date and Time function guide, we explored how Java can be used to handle different tasks involving date and time. This is an essential concept, as many software requires accurate date and time management to work effectively. Now it’s time to put your knowledge into action and do some practicals on Time and Date in Java. Do check out UNext for IIM Indore-certified courses on cutting-edge technologies, making you job-ready within months.

Related Articles

loader
Please wait while your application is being created.
Request Callback