Last Updated:

Java - formatting the date and time

All programmers who learn Java sooner or later are faced with the task of formatting the date and time. Special classes are responsible for this, the main of which are Date and Calendar. They can be used to calculate the current time. Well, you can format the time using another class – SimpleDateFormat. You will learn about this and much more below.

Constructors

The Date class can support two constructors:

NameSynopsis
Date()This constructor initializes an object with the current date and time.
Date(long millisec)The constructor takes the argument = the number of milliseconds that have elapsed since midnight on 1/1970.

Methods of the Date Class

 

NameSynopsis
boolean after(Date date)If the caller date contains a date that was earlier than the specified date, it returns true. Otherwise, it returns false.
boolean before(Date date)If the caller date contains a date earlier than the specified date, the class returns true. In another case, the class returns false.
Object clone()Duplicate the date caller.
  
int compareTo(Date date)The class compares the caller's value to this date. If the values are equal, it returns 0 if the call object is earlier, returns a negative value, if the object is later than the date, it returns a positive one.
int compareTo(Object obj)If the object being called has a Date class, it works in the same way as compareTo(Date). Otherwise, a ClassCastException is thrown.
boolean equals(Object date)If the caller date contains the same time and date that was specified in date, returns true. Otherwise, the class returns false.
long getTime()A class returns the number of milliseconds starting January 1, 1970.
int hashCode()The class returns the hash code for the call object.
void setTime(long time)The class specifies the date and time spent in milliseconds of January 1, 1970.
String toString()The class converts the caller to a string and returns the result.
 

How to get the current date and time in Java

In fact, getting the current date and time in Java is not difficult. For example, you can use a date object with the toString() method. It will look like this:

import java.util.Date;

publicclassTest{

publicstaticvoidmain(String args[]){
// Initialize the date object
Datedate = newDate();

Display the current date and time using toString()
System.out.println(date.toString());
}
}

There are three ways to compare dates in Java:

  1. The getTime() function. It can be used to get the number of milliseconds that have elapsed since January 1, 1970, for both objects, and then compare these figures.
  2. The before(), after(), and equals() methods. For example, new Date(99, 2, 12).before(new Date (99, 2, 18)). Because the 12th is earlier than the 18th of the month, it returns true.
  3. The compareTo() method. It is defined by a comparable interface and then implemented by date.

Format a date by using the SimpleDateFormat class

 

Use the class to parse and format dates for Java. To format the date and time, it allows you to start by selecting a variety of custom templates. Here's an example:

import java.util.*;
importjava.text.*;

publicclassTest{

publicstaticvoidmain(String args[]){
Date dateNow = newDate();
SimpleDateFormat formatForDateNow = newSimpleDateFormat(«E yyyy. MM.dd ‘и время’ hh:mm:ss a zzz»);

System.out.println("Current Date » + formatForDateNow.format(dateNow));
}
}

Get the result of the current date.

SimpleDateFormat code format

 

To set the date and time format in Java, use regular expressions (a string pattern) with a date and time. All ASCII letters in this model are reserved as a letter template, defined as follows:

DescriptionSymbolExample
Designation of the eraGA.D.
Four-digit yearand2020
Month number of the yearM12
Date of the monthd15
Clock format in A.M./P.M.(1~12)h8
Clock format(0~23)H20
Minutesm40
Secondss30
MillisecondsS511
Day of the weekAndW
Number of the day of the yearD350
Weekday number in a monthF3 (third Sunday this month)
Number of the week of the yearin51
Week number in monthIn3
Маркер A.M./P.M.aOn the
Clock Format(1~24)k24
Clock format in A.M./P.M.(0~11)K0
Time zonewithFET (Far Eastern European Time)
Select for textText
Single quotation mark»
 

Format a date by using the printf method

 

It is also convenient and easy to make a date and time format using the printf method. To do this, you need to use the format of 2 letters, starting with t and ending with one of the characters in the table below:

import java.util.Date;

publicclassTest{

publicstaticvoidmain(String args[]){
// Initialize the date object
Datedate = newDate();

Display the current date and time using toString()
String str = String.format("Current date and time: %tc", date);

System.out.printf(str);
}
}

We get the following result:

Current date and time: Tue Dec 1520:55:59 FET 2020

If you had to put a date several times to format each part, that would be silly. Therefore, the format of the string can talk about the index of the argument for formatting. In this case, the index should follow % and end with $. Here's an example:

import java.util.Date;

publicclassTest{

publicstaticvoidmain(String args[]){
// Initialize the date object
Datedate = newDate();

// Display current date using toString()
System.out.printf("%1$s %2$td %2$tB %2$tY", "Date:", date);
}
}

The result will be as follows:

Date: December 15, 2020

In addition, you can use <. This means that the same argument must be applied again as past format specifications. Example:

import java.util.Date;

publicclassTest{

publicstaticvoidmain(String args[]){
// Инициализация объекта date
Date date = newDate();

Output of the formatted date (remove the character = below from the code, otherwise I have a conflict with html)
System.out.printf(%s %te %<=tB %<=tY", "Today's date:", date);

}
}

Let's get the following result:

Today's date: 15 December2020

Date and time conversion symbols

 

You can display the time in the required format in Java using special conversion symbols:

DescriptionSymbolExample
Current time and datecTue Dec 15 20:58:27 FET 2020
ISO 8601 date format (year-month-day)F2020-12-15
American date format (month/day/year)D12/19/20
24-hour time formatT20:58:25
12-hour time formatr20:58:25 AM
24-hour time format without secondsR20:58
Current year of four digits (with leading zeros)And2020
Last two digits of the year (with leading zeros)and20
The first two digits of the year (with leading zeros)C20
Full name of the monthBDecember
Abbreviated name of the monthbDec
Current month number (with leading zeros)m12
Current day of the month number (with leading zeros)d15
Number of the current day of the month (without leading zeros)and15
Full name of the current day of the weekATuesday
Abbreviated name of the day of the weekaW
Number of days since the beginning of the year (with leading zeros)j318
Hour format (with leading zeros), from 00 to 23H21
Clock format (without leading zeros), from 0 to 23k21
Clock format (with leading zeros), from 01 to 12I21
Clock format (without lead zeros), from 1 to 12l21
Minutes (with leading zeros)M58
Seconds (with leading zeros)S25
Milliseconds (with leading zeros)L382
Nanoseconds (with leading zeros)N775000000
Верхний регистр маркера A.M./P.M.p (%Tp)On the
Нижний регистр маркера A.M./P.M.p (%tp)on the
RFC 822 Hourly Offset GMTwith+0300
Time zoneWithFact
Seconds starting from 1970-01-01 00:00:00 GMTs1608059134
Milliseconds starting 1970-01-01 00:00:00 GMTQ16080591341000
 

There are many other useful classes that are related to date and time. To learn more about them, you can refer to the standard Java documentation.

How to convert a string to a date

 

SimpleDateForma has additional methods, including parse(), which helps you translate a string to a date that matches the format stored in the SimpleDateFormat object. Example:

import java.util.*;
importjava.text.*;

publicclassTest{

publicstaticvoidmain(String args[]){
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
Stringstr = args.length == 0 ? 2020-12-15" : args[0];

System.out.print("String " + str + " parsed as ");
Date parsingDate;
try {
parsingDate = ft.parse(str);
System.out.println(parsingDate);
}catch(ParseException e) {
System.out.println("Unparsed with " + ft);
}
}
}

The result will be as follows:

Line 2020-12-15 is broken as TuDec1500:00:00 FET 2020

Time delay

You can reduce or increase the operating time of the program for any required period: from 1 ms to the life of your PC. Here is an example where the standby mode of the following program will be 10 seconds:

import java.util.*;

publicclassTest{
publicstaticvoidmain(String args[]){
try {
System.out.println(newDate() + "\n");
Thread.sleep(10000); // Freezes the entire thread for 10 seconds
System.out.println(newDate() + "\n");
} catch (Exception e) {
System.out.println("Got an exception!");
}
}
}

We get the following result:

Tu Dec1522:42:16 DONE 2020

Tu Dec1522:42:26 DONE 2020

Instead of Thread.sleep(), it is better to use TimeUnit():

TimeUnit.NANOSECONDS.sleep(), TimeUnit.MICROSECONDS.sleep(), TimeUnit.MILLISECONDS.sleep(), TimeUnit.SECONDS.sleep(), TimeUnit.MINUTES.sleep(), TimeUnit.HOURS.sleep() или TimeUnit.DAYS.sleep().

Program Execution Time

 

It is quite simple to find out the execution time of the program code through System.currentTimeMillis(). Just write the system.currentTimeMillis() value to the variable value of the program first. Accordingly, at the end you need to subtract the variable System.currentTimeMillis() from the current value. Here is an example where the speed of the program code will be measured, displaying 10 random numbers on the screen:

import java.util.*;

publicclassTest{
publicstaticvoidmain(String args[]){
// Reference points
long start = System.currentTimeMillis();

The program code. Receiving 10 random numbers from 0 to 9 and displaying
for(int i = 1;i <= 10;i++) {
System.out.println("Random number No" + i + ": " + (int)(Math.random() * 10));
}

Get and write to the variable timeWorkCode of the running time of the program
long timeWorkCode = System.currentTimeMillis() - start;
// Output of the code execution time to the System.out.println screen
("Program execution speed: " + timeWorkCode + " milliseconds");
}
}

The result of the code execution:

Random number #1: 0
Random number #2: 5
Random number #3: 9
Random number #4: 9
Random number #5: 0
Random number #6: 2
Random number #7: 0
Random number #8: 3
Random number #9: 5
Random number #10:9
Program execution speed: 2 milliseconds

Date difference in Java

In some cases, the programmer needs to calculate the difference between the dates, find out the point in time in ms. Let's rewrite the example above:

import java.util.*;

publicclassTest{

publicstaticvoidmain(String args[]){
try {
long start = System.currentTimeMillis();
System.out.println(newDate() + «\n»);

Thread.sleep(10000);
System.out.println(newDate() + «\n»);

long end = System.currentTimeMillis();
long diff = end — start;
System.out.println(«Разница между датами: » + diff + » миллисекунд»);
}catch (Exception e) {
System.out.println(«Получили исключение!»);

}
}
}

The result of the code execution:

Tu Dec1522:22:10 DONE 2020

Tu Dec1522:22:20 DONE 2020

Date difference: 10081 milliseconds

Number of days between dates

 

You may also be faced with the task of calculating the number of days, hours, minutes, and so on between dates. Here is one way to find the days between two dates:

import java.util.*;

publicclassTest{

publicstaticvoidmain(String args[]){
String date1 = «01.03.2016»;
String date2 = «01.02.2016»;

SimpleDateFormat format = new SimpleDateFormat(«dd.MM.yyyy»);

Date dateOne = null;
Date dateTwo = null;

try {
dateOne = format.parse(date1);
dateTwo = format.parse(date2);
} catch (Exception e) {
e.printStackTrace();

}

Number of days between dates in milliseconds
long difference = dateOne.getTime() — dateTwo.getTime();
// Convert the number of days between dates from milliseconds to
days int days = (int)(difference / (24 * 60 * 60 * 1000)); milliseconds / (24h * 60min * 60sec * 1000ms)
// Display the difference between dates in days on the screen
System.out.println(days + » days");

}
}

We get the following result:

29 days

GregorianCalendar class

 

The GregorianCalendar class is a specific implementation of the Calendar class that displays an ordinary Gregorian calendar.

The getInstance() Calendar method returns GregorianCalendar, which by default is initialized with the current date and time, localization, and time zone. GregorianCalendar defines 2 fields: AD and B.C. These are two epochs defined by the Gregorian calendar.

Constructors for GregorianCalendar objects:

Constructor NameSynopsis
GregorianCalendar()Creates a GregorianCalendar using the current date and time, localization, and default time zone.
GregorianCalendar(int year, int month, int date)Creates a GregorianCalendar value based on the specified date in the time zone and default localization.
GregorianCalendar(int year, int month, int date, int hour, int minute)Constructs the GregorianCalendar according to the specified date and time in the time zone and default localization.
GregorianCalendar(int year, int month, int date, int hour, int minute, int second)Constructs the GregorianCalendar according to the specified date and time in the time zone and default localization.
GregorianCalendar(Local toLocal)Generates a GregorianCalendar according to the current time in the default time zone within the specified localization.
GregorianCalendar(TimeZone zone)Creates a GregorianCalendar based on the current time in a given time zone with default localization.
GregorianCalendar(TimeZone zone, Locale aLocale)Generates a GregorianCalendar based on the current time in the specified time zone and localization.
 

Useful methods of the GregorianCalendar class:

 

MethodDescription
void add(int field, int amount)Adds the specified amount of time to this time field according to calendar rules.
protected void computeFields()Converts UTC time to milliseconds to the value of the time fields.
protected void computeTime()Converts the values of the Calendar temporary field in UTC format in milliseconds.
boolean equals(Object obj)Compares this GregorianCalendar to a reference object.
int get(int field)Gets the value for the specified time field.
int getActualMaximum(int field)Returns the maximum value this field can have given the current date.
int getActualMinimum(int field)Returns the minimum value this field can have given the current date.
int getGreatestMinimum(int field)Returns the highest minimum value for a given field if modified.
Date getGregorianChange()Gets the date changes from the Gregorian calendar.
int getLeastMaximum(int field)Returns the minimum maximum value for this field if it changes.
int getMaximum(int field)Returns the maximum value for this field.
Date getTime()Specifies the current time according to the calendar.
long getTimeInMillis()Gets the current calendar time as long.
TimeZone getTimeZone()Returns the time zone.
int getMinimum(int field)Returns the minimum value for this field.
int hashCode()Override the hash code.
boolean isLeapYear(int year)Determines whether the year is a leap year.
void roll(int field, boolean up)Add or subtract (up/down) a single unit of time in a given time field without changing the large fields.
void set(int field, int value)Sets a temporary field with the specified value.
void set(int year, int month, int date)Specifies values for the Year, Month, and Date field.
void set(int year, int month, int date, int hour, int minute)Specifies values for the Year, Month, Date, Hour, and Minute fields.
void set(int year, int month, int date, int hour, int minute, int second)Specifies values for the Year, Month, Date, Hour, Minute, and Second fields.
void setGregorianChange(Date date)Sets the date when the Gregorian calendar was modified.
void setTime(Date date)Sets the current time according to this calendar with the specified date.
void setTimeInMillis(long millis)Sets the current time from the specified long value according to this calendar.
void setTimeZone(TimeZone value)Specifies the time zone with the value of the specified time zone.
String toString()Returns a string representation of the calendar.
 

We hope our examples helped you to understand how to work with the date and time in Java. If you have any questions, you can ask them in the comments.