Part 14: Date and Time in Java with real time Example.

JAVA | 186 comments

 Date and Time in Java

Example of Constructor

  1. Date( ) this constructor initializes the object with the current date and time.
  2. Date(long millisec) this constructor accepts an argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970.

Following are the some methods of the date class.

Method Description
boolean after(Date date) Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.
boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false.
Object clone( ) Duplicates the invoking Date object.
int compareTo(Date date) Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the invoking object is earlier than date. Returns a positive value if the invoking object is later than date.
int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.
boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false.
long getTime( ) Returns the number of milliseconds that have elapsed since May 1, 2020.
int hashCode( ) Returns a hash code for the invoking object.
void setTime(long time) Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, May 1, 2020.
String toString( ) Converts the invoking Date object into a string and returns the result.

Getting Current Date and Time

This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows:

Example

import java.util.Date;

public class ExampleDateDemo {

   public static void main(String args[]) {

      Date date = new Date(); // This statement Instantiate a Date object

      System.out.println(date.toString()); // display time and date using toString()

   }

}

This will produce the following result:

Output

Mon Jun 07 11:55:32 UTC 2021

Date Comparison

Following are the three ways to compare two dates:

  • Method getTime( ) to obtain the number of milliseconds that have passed since midnight, June 1, 2021, for both objects and then compare these two values.
  • methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 21).before(new Date (99, 2, 21)) returns true.
  • Method compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

Date Format Using SimpleDateFormat class:

SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner.  This class allows you to start by choosing any user-defined patterns for date-time formatting.

Example

import java.util.*;

import java.text.*;

public class ExampleDateDemo {

   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));

   }

}

This will produce the following result:

Output

Current Date: Mon 2021.06.07 at 01:04:15 PM UTC

Simple DateFormat Format Codes

In order to specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following:

Character            Description 
G             Era designator, Example: AD
y              Year in four digits, Example: 2001
M            Month in year,  Example: July or 07
d             Day in month,    Example: 10
h             Hour in A.M./P.M. (1~12) Example:12
H             Hour in day (0~23), Example:22
m            Minute in hour  30, Example:
s              Second in minute, Example:55
S              Millisecond Example:234
E              Day in week Example:Tuesday
D             Day in year Example:360
F              Day of week in month    Example:2 (second Wed. in July)
w            Week in year      Example:40
W            Week in month Example:1
a              A.M./P.M. marker           Example:PM
k              Hour in day (1~24)           Example:24
K             Hour in A.M./P.M. (0~11)             Example:10
z              Time zone           Example:Eastern Standard Time
‘               Escape for text  Delimiter
”              Single quote       `

Date Format Using printf

Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code.

Example

import java.util.Date;

public class ExampleDateDemo {

   public static void main(String args[]) {

      Date date = new Date(); // Instantiate a Date object

      String str = String.format("Current Date/Time : %tc", date );       // display time and date

      System.out.printf(str);

   }

}

This will produce the following result −

Output

Current Date/Time : Mon Jun 07 13:08:21 UTC 2021

It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the % and it must be terminated by a $.

Example

import java.util.Date;

public class DateDemo {

   public static void main(String args[]) {    

      Date date = new Date();// Instantiate a Date object      

      System.out.printf("%1$s %2$tB %2$td, %2$tY", "Due date:", date);// display time and date

   }

}

This will produce the following result:

Output

Due date: June 07, 2021

Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again.

Example

import java.util.Date;

public class ExampleDateDemo {

   public static void main(String args[]) {

      Date date = new Date(); // This statement Instantiate a Date object

      System.out.printf("%s %tB %<te, %<tY", "Due date:", date); // This statement display formatted date

   }

}

This will produce the following result −

Output

Due date: June 7, 2021

Date and Time Conversion Characters

Character Description
c Complete date and time; Example: Mon May 04 09:51:52 CDT 2009
F ISO 8601 date
D U.S. formatted date (month/day/year). Example: 02/09/2004
T 24-hour time
r 12-hour time
R 24-hour time, no seconds. Example:
Y Four-digit year (with leading zeroes). Example:
y Last two digits of the year (with leading zeroes). Example:
C First two digits of the year (with leading zeroes)
B Full month name
b Abbreviated month name
m Two-digit month (with leading zeroes)
d Two-digit day (with leading zeroes)
e Two-digit day (without leading zeroes)
A Full weekday name
a Abbreviated weekday name. Example:
j Three-digit day of year (with leading zeroes) . Example:
H Two-digit hour (with leading zeroes), between 00 and 23
k Two-digit hour (without leading zeroes), between 0 and 23
I Two-digit hour (with leading zeroes), between 01 and 12
l Two-digit hour (without leading zeroes), between 1 and 12
M Two-digit minutes (with leading zeroes) . Example:
S Two-digit seconds (with leading zeroes)
L Three-digit milliseconds (with leading zeroes)
N Nine-digit nanoseconds (with leading zeroes)
P Uppercase morning or afternoon marker
p Lowercase morning or afternoon marker
z RFC 822 numeric offset from GMT
Z Time zone
s Seconds since 1970-01-01 00:00:00 GMT. Example:
Q Milliseconds since 1970-01-01 00:00:00 GMT. Example:

There are other useful classes related to Date and time. For more details, you can refer to Java Standard documentation.

Parsing Strings into Dates

The SimpleDateFormat class has some additional methods, notably parse( ), which tries to parse a string according to the format stored in the given SimpleDateFormat object.

Example

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);

}

}

}

A sample run of the above program would produce the following result −

Output

1818-11-11 Parses as Wed Nov 11 00:00:00 UTC 1818

Sleep for a While

You can sleep for any period of time from one millisecond up to the lifetime of your computer. For example, the following program would sleep for 3 seconds −

Example

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!”);

}

}

}

This will produce the following result:

Output

Mon Jun 07 13:13:30 UTC 2021

Mon Jun 07 13:13:33 UTC 2021

Measuring Elapsed Time

Sometimes, you may need to measure point in time in milliseconds. So let’s re-write the above example once again −

Example

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!”);

}

}

}

This will produce the following result :

Output

Mon Jun 07 13:14:57 UTC 2021

Mon Jun 07 13:15:00 UTC 2021

Difference is : 3036

GregorianCalendar Class

GregorianCalendar is a concrete implementation of a Calendar class that implements the normal Gregorian calendar with which you are familiar. We did not discuss Calendar class in this tutorial, you can look up standard Java documentation for this. The getInstance( ) method of Calendar returns a GregorianCalendar initialized with the current date and time in the default locale and time zone. GregorianCalendar defines two fields: AD and BC. These represent the two eras defined by the Gregorian calendar. There are also several constructors for GregorianCalendar objects:

Constructor Description
GregorianCalendar() This Constructor constructs a default GregorianCalendar using the current time in the default time zone with the default locale.
GregorianCalendar(int year, int month, int date) This Constructor constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
GregorianCalendar(int year, int month, int date, int hour, int minute) This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(int year, int month, int date, int hour, int minute, int second) This Constructor constructs a GregorianCalendar with the given date and time set for the default time zone with the default locale.
GregorianCalendar(Locale aLocale) This Constructor constructs a GregorianCalendar based on the current time in the default time zone with the given locale.
GregorianCalendar(TimeZone zone) This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the default locale.
GregorianCalendar(TimeZone zone, Locale aLocale) This Constructor constructs a GregorianCalendar based on the current time in the given time zone with the given locale.

Here is the list of few useful support methods provided by GregorianCalendar class:

Method Description
void add(int field, int amount) Adds the specified (signed) amount of time to the given time field, based on the calendar’s rules.
protected void computeFields() Converts UTC as milliseconds to time field values.
protected void computeTime() Overrides Calendar Converts time field values to UTC as milliseconds.
boolean equals(Object obj) Compares this GregorianCalendar to an object reference.
int get(int field) Gets the value for a given time field.
int getActualMaximum(int field) Returns the maximum value that this field could have, given the current date.
int getActualMinimum(int field) Returns the minimum value that this field could have, given the current date.
int getGreatestMinimum(int field) Returns highest minimum value for the given field if varies.
Date getGregorianChange() Gets the Gregorian Calendar change date.
int getLeastMaximum(int field) int getLeastMaximum(int field) Returns lowest maximum value for the given field if varies.
int getMaximum(int field) Returns maximum value for the given field.
Date getTime() Gets this Calendar’s current time.
long getTimeInMillis() Gets this Calendar’s current time as a long.
TimeZone getTimeZone() Gets the time zone.
int getMinimum(int field) Returns minimum value for the given field.
int hashCode() Overrides hashCode.
boolean isLeapYear(int year) Determines if the given year is a leap year.
void roll(int field, boolean up) Adds or subtracts (up/down) a single unit of time on the given time field without changing larger fields.
void set(int field, int value) Sets the time field with the given value.
void set(int year, int month, int date) Sets the values for the fields year, month, and date.

Example

import java.util.*;

public class ExampleGregorianCalendarDemo {

public static void main(String args[]) {

String months[] = {“Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”,

“Oct”, “Nov”, “Dec”};

int year;   // Create a Gregorian calendar initialized  with the current date and time in the default timezone.

GregorianCalendar gcalendar = new GregorianCalendar();

System.out.print(“Date: “);// Display current time and date information.

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)) { // Test if the current year is a leap year

System.out.println(“The current year is a leap year”);

}else {

System.out.println(“The current year is not a leap year”);

}

}

}

This will produce the following result −

Output

Date: Jun 7 2021
Time: 1:16:54
The current year is not a leap year

For a complete list of constant available in Calendar class, you can refer the standard Java documentation.

Java Dates does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes. For example:

  • LocalDate class: Represents a date (year, month, day (yyyy-MM-dd))
  • LocalTime class: Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns))
  • LocalDateTime  class: Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)
  • DateTimeFormatter class:Formatter for displaying and parsing date-time objects

If you don’t know what a package is, read our Java Packages article .

Current Date

To display the current date, import the java.time. LocalDate class, and use its now() method:

Example

import java.time.LocalDate; // import the LocalDate class

public class ExampleMain {

  public static void main(String[] args) {

    LocalDate myObj = LocalDate.now(); // This is Create a date object

    System.out.println(myObj); // This is Display the current date

  }

}

The output will be:

2021-06-07

Current Time 

To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method:

Example

import java.time.LocalTime; // This is import the LocalTime class

public class ExapleMain {

  public static void main(String[] args) {

    LocalTime myObj = LocalTime.now();

    System.out.println(myObj);

  }

}

The output will be:

14:47:34.528

Display Current Date and Time

In order to display the current date and time, import the java.time.LocalDateTime class, and use its now() method:

Example

import java.time.LocalDateTime; // import the LocalDateTime class

public class ExampleMain {

public static void main(String[] args) {

LocalDateTime myObj = LocalDateTime.now();

System.out.println(myObj);

}

}

The output will be:

2021-06-07T14:48:24.914

Formatting Date and Time

The “T” in the example above is used to separate the date from the time. You can use the DateTimeFormatter class with the ofPattern() method in the same package to format or parse date-time objects. The following example will remove both the “T” and nanoseconds from the date-time:

Example

import java.time.LocalDateTime; // This Import the LocalDateTime class

import java.time.format.DateTimeFormatter; //This Import the DateTimeFormatter class

public class ExampleMain {

  public static void main(String[] args) {

    LocalDateTime myDateObj = LocalDateTime.now();

    System.out.println("Before formatting: " + myDateObj);

    DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

    String formattedDate = myDateObj.format(myFormatObj);

    System.out.println("After formatting: " + formattedDate);

  }

}

output:

Before formatting: 2021-06-07T14:50:38.049
After formatting: 07-06-2021 14:50:38

The ofPattern() method receive all of values, if you want to display the date and time in a different format. For example:

Value

yyyy-MM-dd      Example:  “2020-05-29″

dd/MM/yyyy     Example:”29/05/2020″

dd-MMM-yyyy Example:”29-May -2020″

E, MMM dd yyyy  Example:”Thu, May 29 2020”

Chapter 6: Software Testing with example Process

What is Testing? Testing is the process of evaluating a system or its component(s) with the intent to find whether it satisfies the specified requirements or not. In simple words, testing is executing a system in order to identify any gaps, errors, or missing...

Chapter – 4: Project management with Example Procedures.

Project management Software project management is an essential part of software engineering. Projects need to be managed because professional software engineering is always subject to organizational budget and schedule constraints. The project manager‘s job is to...

You may find interest following article

Chapter 6: Software Testing with example Process

What is Testing? Testing is the process of evaluating a system or its component(s) with the intent to find whether it satisfies the specified requirements or not. In simple words, testing is executing a system in order to identify any gaps, errors, or missing requirements in contrary to the actual requirements. According to ANSI/IEEE 1059 standard, Testing can be...

Chapter-5: Cost Estimation Tutorial in Software Engineering

Cost Estimation Tutorial Cost is s strategic concept in software development for the following reasons: Project management: Estimating cost is extremely crucial in carrying out project management activities such as scheduling, planning and control.Feasibility Study: Making investment decisions regarding software projects requires full cost breakdown and analysis...

Chapter – 4: Project management with Example Procedures.

Project management Software project management is an essential part of software engineering. Projects need to be managed because professional software engineering is always subject to organizational budget and schedule constraints. The project manager‘s job is to ensure that the software project meets and overcomes these constraints as well as delivering...

Chapter -3: Agile Software Development Method Process

Agile Software Development Although there are many approaches to rapid software development, they share some fundamental characteristics: The processes of specification, design, and implementation are interleaved. There is no detailed system specification, and design documentation is minimized or generated automatically by the programming environment used to...

Chapter 2: Software processes with various model

Objectives: understand the concepts of software processes and software process models;have been introduced to three generic software process models and when they might be used;know about the fundamental process activities of software requirements engineering, software development, testing, and evolution;understand why processes should be organized to cope with...

Frequency Word for IELTS Listening

Frequency Word for IELTS Listening School a. Library  WordSentence1. Shelf 2. Librarian 3. The stacks 4. Return 5. Fine 6. Magazine 7. Copier  8. Overdue  9. Reading room  10. Reference room  11. Periodical room  12. Study lounge  13. Catalogue  14....

Chapter 8: Gantt chart Project Development in SDLC

Gantt chart Project DevelopmentSchedule (project management) The project scheduleis the tool that communicates what work needs to be performed, which resources of the organization will perform the work and the timeframes in which that work needs to be performed. The project scheduleshould reflect all of the work associated with delivering the project on time....

Chapter 7: Feasibility Analysis in Software Develoment Life Cycle.

Feasibility AnalysisWhat is Feasibility Analysis?? An analysisand evaluation of a proposed project to determine if it (1) is technically feasible, (2) is feasible within the estimated cost, and (3) will be profitable for Organization. Feasibility analysis guides the organization in determining whether to proceed with the project. Feasibility analysis also identifies...

Chapter 6: Data Flow Diagram in Software Development Life Cycle.

Data Flow Diagram What is DFD? A data flow diagram (DFD) is a graphical representation of the "flow" of data through an information system, modelling its process aspects.A DFD is often used as a preliminary step to create an overview of the system, which can later be elaborated.Show users how data moves between different processes in a system. Figure 1: DFD Symbols...

Chapter 5: System request on SDLC

System Request In most organizations, project initiation begins by preparing a  system request. A  system request is a document that describes the business reasons for building a system and the value that the system is expected to provide.The project sponsor usually completes this form as part of a formal system project selection process within the...

Chapter 4: SDLC design Phase

SDLC design Phase DFD (Design Analysis)Architectural DesignUI DesignDatabase DesignProgram DesignArchitectural design (logical)Network designClient –server designClient designServer designCloud ComputingDatabase designER diagramRelational diagramDDL (not now..!!)Program design (physical)Investigating the hardware/software platformPhysical DFDData storageData...

Chapter 3: SDLC and its Life cycle Phases.

What is SDLC? The systems development life cycle (SDLC), also referred to as the application development life-cycle, is a term used in systems engineering, information systems and software engineering to describe a process for planning, creating, testing, and deploying an information system. Career Paths for System Developers Systems Development Life Cycle Building...

Chapter 2: SDLC Key Features For SYSTEMS ANALYST.

Once upon a time, software development consisted of a programmer writing code to solve a problem or automate a procedure. Nowadays, systems are so big and complex that teams of architects, analysts, programmers, testers and users must work together to create the millions of lines of custom-written code that drive our enterprises.To manage this, a number of system...

Chapter 1: System analysis and Design Overview.

System analysis, a method of studying a system by examining its component parts and their interactions. •It provides a framework in which judgments of the experts in different fields can be combined to determine what must be done, and what is the best way to accomplish it in light of current and future needs.  •The system analyst (usually a software engineer or...

Chapter 4: Concept Of Sampling, Quantization And Resolutions

Concept Of Sampling, Quantization And Resolutions Conversion of analog signal to digital signal: The output of most of the image sensors is an analog signal, and we can not apply digital processing on it because we can not store it. We can not store it because it requires infinite memory to store a signal that can have infinite values. So we have to convert an...

Chapter 3: Images and Conversions in Digital Image Process

Images And Conversions There are many type of images, and we will look in detail about different types of images, and the color distribution in them. The binary image The binary image as it name states, contain only two pixel values. 0 and 1. In our previous tutorial of bits per pixel, we have explained this in detail about the representation of pixel values to...

Chapter 2: Concept of Pixel in Digital Image Process

Concept of Pixel Pixel Pixel is the smallest element of an image. Each pixel correspond to any one value. In an 8-bit gray scale image, the value of the pixel between 0 and 255. The value of a pixel at any point correspond to the intensity of the light photons striking at that point. Each pixel store a value proportional to the light intensity at that particular...

Part 6: IELTS Academic Writing Task 1 For Diagram/Graph Vocabulary

Vocabulary to show the sequence: You must write a summary of at least 150 words in response to a specific graph (bar, line, or pie graph), table, chart, or procedure in Writing Task 1 of the IELTS Academic test (how something works, how something is done). This job assesses your ability to choose and report the most important aspects, describe and compare data,...

Part 5: IELTS Academic Writing Task 1 Formal and Informal expressions.

Formal and Informal expressions and words: You must write a summary of at least 150 words in response to a specific graph (bar, line, or pie graph), table, chart, or procedure on the IELTS Academic test (how something works, how something is done). Few more informal expressions with their formal versions are given below. Since IELTS is a formal test, your writing...