Date and Time API in Java

Mahesh Sharma
16 min readFeb 18, 2024

Date and Time API in Java

Java provides an API to display or retrieve the current date and time of the system. The classes which represent the date and time are present in the java.time, java.util, java.sql, and java.text packages.

These classes play a major role in dealing with date and time.

Example:

// program to print the current time and date

import java.time.format.DateTimeFormatter;

import java.time.LocalDateTime;

class HelloWorld {

public static void main(String[] args) {

// creating object to the DateTimeFormatter class

DateTimeFormatter d = DateTimeFormatter.ofPattern(“yyyy/MM/dd HH:mm:ss”);

// creating object to the LocalDateTime class

LocalDateTime present = LocalDateTime.now();

System.out.println(“ The current date and time is: “);

System.out.print(d.format(present));

}

}

Output:

Java Date and Time APIs

In java, the functionality of date and time can be performed using java.time and java.util packages. The java.time was introduced in java 8 version. The java.time package is introduced to overcome the drawbacks of the current APIs

Classical Date Time API Classes

1. java.lang.System

2. java.util.date

3. java.util.Calendar

4. java.text.SimpleDateFormat

5. java.util.TimeZone

are the primary classes before java 8 was released.

1. java.lang.System: java.lang.System class is used to display the current system time in milliseconds using currentTimeMillis() method, which is present in the System class in java.lang package. By using this method, we can display the date and time from 1st January 1970.

Example:

// program to print current time in milliseconds using currentTimeMillis method

import java.lang.System;

class HelloWorld

{

public static void main(String args[])

{

System.out.println(“ current time in milliseconds is: “);

// calling the currentTimeMillis method to print the current time in milliseconds

System.out.print(System.currentTimeMillis());

}

}

Output:

2. java.util.date: java.util.date class is used to display the current instance of the date and time. The constructors and method which deal with date and time are provided in this class. This class is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

Example:

// program to print the current date and time using java.util.Date class

import java.util.Date;

import java.lang.*;

class HelloWorld

{

public static void main(String args[])

{

System.out.println(“ current time of the System is : “);

// we can display the date and time in 2 ways

// first way

System.out.println(“ Current date and time using first way is: “);

Date d = new Date(); // creating object to date class

System.out.println(d);

// Second way

// by calling the currentTimeMillis() method and passing the output in Date constructure

System.out.println(“ Current date and time using second way is: “);

long m = System.currentTimeMillis();

Date da = new Date(m); // creating object to date class

System.out.println(da);

}

}

Output:

3. java.text.SimpleDateFormat: java.text.SimpleDateFormat class is used to display the current date and time in the predefined pattern or in user-defined pattern.

Example:

// program to print current date using java.text.SimpleDateFormat class

import java.text.SimpleDateFormat;

import java.util.Date;

class HelloWorld

{

public static void main(String args[])

{

System.out.println(“ current date of the System is : “);

Date d = new Date(); // creating object to date class

// fixing the formate of the date in dd/mm/yyyy format

SimpleDateFormat f = new SimpleDateFormat(“dd/MM/yyyy”);

String date= f.format(d); // calling the format() method and passing the object

System.out.println(date); //printing the date

}

}

Output:

4. java.util.TimeZone: It represents a time zone offset and also figures out daylight savings.

Example:

// program to print the offset of the current time zone using java.util.TimeZone class

import java.util.*;

import java.util.Date;

import java.util.TimeZone;

class HelloWorld

{

public static void main(String args[])

{

String[] id = TimeZone.getAvailableIDs();

// creating the object to the TimeZone class

TimeZone z = TimeZone.getTimeZone(“Asia/Kolkata”);

// printing the current time zone offset

System.out.println(“The Offset value of TimeZone: “ +

z.getOffset(Calendar.ZONE_OFFSET));

}

}

Output:

Example 2:

// program to print the id value current time zone using java.util.TimeZone class

import java.util.*;

import java.util.Date;

import java.util.TimeZone;

class HelloWorld

{

public static void main(String args[])

{

// creating the object to the TimeZone class

TimeZone timezone = TimeZone.getTimeZone(“Asia/Kolkata”);

// printing the id of the Asia/ Kolkata time zone

System.out.println(“ The Id value of the current time zone is: “ + timezone.getID());

}

}

Output:

Example 3:

// program to print the current time zone name — using java.util.TimeZone class

import java.util.*;

import java.util.Date;

import java.util.TimeZone;

class HelloWorld

{

public static void main(String args[])

{

// creating the object to the TimeZone class and calling the getDefault() method

TimeZone z= TimeZone.getDefault();

String name = z.getDisplayName();

// printing the name of the default time zone

System.out.println(“Display name for default time zone: “+ name);

}

}

Output:

Drawbacks of Existing Date and Time API

1. Thread safety: The Date and calendar classes do not provide thread safety. Due to no proper thread safety, it leads hard to debug concurrency issues.

2. Bad API design: In classic classes like date and calendar, the method to perform day-to-day functionalities is not provided.

3. Complex time zone handling: To handle the time zone, the developer is supposed to write the logic for it.

New Date Time API in Java 8

To overcome the drawbacks of the classical API, a new API related to date and time is introduced in java 8. The classes

1. java.time.LocalDate

2. java.time.LocalTime

3. java.time.LocalDateTime

4. Java.time.ZonedDateTime

5. java.time.OffsetTime

6. java.time.OffsetDateTime

7. java.time.Clock,

8. java.time.Instant

9. java.time.Duration

10. java.time.Period

11. java.time.Zoned

12. java.time.ZoneOffset

13. java.time.DateTimeFormatter

are present in the time package, which is introduced in java 8.

1. java.time.LocalDate: LocalDate is a class present in the time package. By this, we can print the current system date without printing the current time. By using this, we can print only the date in the year-month-day format. This class is inherited by the object class, and it is implemented by the ChronoLocalDate interface.

Example:

// program to print the Today, Yesterday, and tomorrow’s date using

// java.time.LocalDate class

import java.time .*;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“Hello, World!”);

// creating an object to the LocalDate class and calling the now() method to get the current date

LocalDate date = LocalDate.now(); // current date

// calling the minusDays() method to get Yesterday’s date

LocalDate yesterday = date.minusDays(1); // yesterday date

// calling the plusDays() method to get tomorrow’s date

LocalDate tomorrow = Yesterday.plusDays(2); // tomorrow date

System.out.println(“Today’s date is: “+date); // printing the today’s date

//printing the Yesterday’s date

System.out.println(“Yesterday’s date is: “+yesterday);

// printing tomorrow’s date

System.out.println(“Tomorrow’s date is: “+tomorrow);

}

}

Output:

2. java.time.LocalTime: LocalDate is a class present in the time package. By this, we can print the current system time without printing the current date.

By using this, we can print only the time in the hours:minutes: seconds format. This class is inherited by the object class, and it is implemented by the comparable interface.

Example:

// program to print the current time using java.time.LocalTime class

import java.time .*;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“Hello, World!”);

// creating an object to the LocalTime class and calling the now() method

LocalTime time = LocalTime.now();

System.out.println(“ The current time is: “);

System.out.println(time); // printing the current time

}

}

Output:

3. java.time.LocalDateTime: LocalDateTime is a class present in the time package. By this, we can print the current system time and current date. But we can’t print the time zone of the system.

We can print the date and time in the desired format using the formatDateTimeFormatter class. This class is inherited by object class, and it is implemented by the ChronoLocalDateTime interface.

Example:

// program to print the current date and time using java.time.LocalDateTime class

import java.time .*;

import java.time.format.DateTimeFormatter;

class HelloWorld {

public static void main(String[] args) {

// creating the object to the LocalDateTime class and calling the now() method

LocalDateTime now = LocalDateTime.now();

// printing the current date and time in the default format

System.out.println(“Before Formatting the format of date and time is: \n “ + now);

// defining the format using the DateTimeFormatter class

// creating the object to the DateTimeFormatter class

DateTimeFormatter format = DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss”);

String formatDateTime = now.format(format);

// printing the current date and time in user-defined format

System.out.println(“After Formatting the format of date and time is: \n” + formatDateTime);

}

}

Output:

4. java.time.ZonedDateTime: ZonedDateTinme is a class present in the time package. By this, we can print the current system time and the current date with the time zone information. It is the combination of date, time, and time zone classes. This class is inherited by the object class, and it is implemented by the ChronoZonedDateTime interface.

Example:

// program to print the current date and time with time zone using java.time.ZoneDateTime class

import java.time .*;

import java.time.Period;

import java.time.ZonedDateTime;

class HelloWorld {

public static void main(String[] args) {

// creating the object to the ZoneDateTime class and calling the now() method

ZonedDateTime zone= ZonedDateTime.now();

// creating the object to the ZoneDateTime class and calling the minus() method

ZonedDateTime m = zone.minus(Period.ofDays(126));

// printing the current date and time with the time zone

System.out.println(“ The current date and time with time zone is : \n “);

System.out.println(m);

}

}

Output:

5. java.time.OffsetTime: java.time.OffsetTime is a class present in the time package. By this, we can print the current time zone offset from Greenwich/UTC without a time zone ID. For this class, we don’t require a time zone ID to print the time zone offset. This class is inherited by the object class, and it is implemented by the Comparable interface.

Example:

// program to print the current time zone without time zone id using java.time.OffsetTime class

import java.time .*;

import java.time.OffsetTime;

class HelloWorld {

public static void main(String[] args)

{

// creating the object to the OffsetTime class

OffsetTime offset = OffsetTime.now();

// getting the information of hours

int h = offset.getHour();

System.out.println(h+ “ hour”); // printing the hours

// getting the information of minutes

int m = offset.getMinute();

System.out.println(m+ “ minute”); // printing the minutes

// getting the information of seconds

int s = offset.getSecond();

System.out.println(s+ “ second”); // printing the seconds

}

}

Output:

6. java.time.OffsetDateTime: java.time.OffsetDateTime is a class present in the time package. We can print the current date and day with the corresponding time zone. This class is inherited by the object class and it is implemented by Comparable interface.

Example:

// program to print today’s date and day using the OffsetDateTime class

import java.time .*;

import java.time.OffsetDateTime;

class HelloWorld {

public static void main(String[] args)

{

System.out.println(“ Hello World! “);

// creating the object to OffsetDateTime class and calling the now() method

OffsetDateTime offsetDT = OffsetDateTime.now();

// printing today’s date

System.out.println(“ Today’s date is: “ + offsetDT.toLocalDate());

// printing the today’s day

System.out.println(“ Today’s day is: “ + offsetDT.getDayOfWeek());

}

}

Output:

7. java.time.Clock: java.time.Clock is a class present in the time package. By this, we can print the current date and time at any time zone. This class is an optional class. By this, we can compare the time in different time zones. In this class, we can print the date, time, offset, offset id, time zone, etc. This class is inherited by object class and it is implemented by the comparable interface.

// program to print the current time, date, time zone, and offset using java.time.Clock class

import java.time.Clock;

import java.time.Duration;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“Hello, World!”);

// creating the object to the Clock class

Clock c = Clock.systemDefaultZone();

// printing the current time zone using get one() method

System.out.println(“ The current time zone is: “ + c.getZone());

// printing the current instance of date and time using instant() method

System.out.println(“ The current date and time at this instance is: “ + c.instant());

// creating the object to the Duration class

Duration d = Duration.ofHours(5);

Clock clock = Clock.offset(c, d);

System.out.println(“ The current date and time at this instance is: “ + clock.instant());

}

}

Output:

8. java.time.Instant: java.time.Instant is a class present in a time package. By this, we can print the current instance of time. This class is inherited by the object class, and it is implemented by the Comparable interface.

// program to print the current time, date, time zone, and offset using java.time.Clock class

import java.time.Instant;

import java.time.Duration;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“Hello, World!”);

// creating an object to Instant class and calling now() method

Instant in = Instant.now();

// printing the current instance of time

System.out.println(“ The current instance of time is “ + in);

// creating the object to Instant class and calling the parse() method

Instant ins = Instant.parse(“2022–08–23T09:22:54.847328Z”);

// calling the minus() method and ofDays() method od Duration class

ins = ins.minus(Duration.ofDays(125));

System.out.println(“ The instance of date and time after subtracting 125 days from current date and time is: “ + ins);

Instant in1 = Instant.parse(“2022–08–23T09:22:54.847328Z”);

// calling the plus() method and ofDays() method od Duration class

Instant in2 = in1.plus(Duration.ofDays(125));

System.out.println(“The instance of date and time after subtracting 125 days from current date and time is: “ + in2);

}

}

Output:

9. java.time.Duration: java.time.Duration is a class present in the time package. By this, we can print the DurationDuration of the date and time. By this, we can print the future or past date and time. This class is inherited by the object class, and it is implemented by the Comparable interface. We can find the difference between the current time and the future or past time.

Example:

// program to print the DurationDuration using java.time.Duration class

import java.time .*;

import java.time.temporal.ChronoUnit;

class HelloWorld {

public static void main(String[] args)

{

System.out.println(“ Hello World! “);

// creating an object to Duration class and calling the between method

Duration a = Duration.between(LocalTime.NOON,LocalTime.MAX);

// printing the DurationDuration between the LocalTime.NOON and LocalTime.MAX

System.out.println(“ The duration between LocalTime.NOON and LocalTime.MAX is: “ + a.get(ChronoUnit.SECONDS));

// creating an object to Duration class and calling the between method

Duration a1 = Duration.between(LocalTime.NOON,LocalTime.MAX);

System.out.println(“ The duration difference between LocalTime.NOON and LocalTime.MAX: “ + a1.getSeconds());

Duration a2 = a1.plus(a1);

System.out.println(“ The duration after adding the duration: “ + a2.getSeconds());

// creating an object to Duration class and calling the between method

Duration a3 = Duration.between(LocalTime.NOON,LocalTime.MAX);

System.out.println(“ The duration difference between LocalTime.NOON and LocalTime.MAX: “ + a1.getSeconds());

Duration a4 = a1.minus(a1);

System.out.println(“ The duration after subtracting the duration: “ + a2.getSeconds());

}

}

Output:

10. java.time.Period: java.time.Period is a class present in the time package. By this, we can print the current date and time. In this class, we can print the difference between the dates based on their formats. This class is inherited by the object class, and it is implemented by the ChronoPeriod interface.

Example:

// program to print the date after adding 30 days to the current date and show the implementation of period methods using java.time.Period class

import java.time.*;

import java.time.Period;

import java.time.temporal.Temporal;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“Hello, World!”);

// creating an object to the Period class and calling the ofDays() method

Period p = Period.ofDays(30);

// creating the object to the Temporal class and finding the current date

Temporal t = p.addTo(LocalDate.now());

// printing the date of the day after adding 30 days

System.out.println(“ The date of the day after adding the 30 days to the current date is: “ + t);

//changing date into a string

// creating an object to the Period class and calling the of() method

Period pe = Period.of(2020,8,24);

System.out.println(“ The converted date into string is: “ + pe.toString());

// creating an object to the Period class and calling the of() method

Period p1 = Period.ofMonths(4);

// calling the plus() method of Period class

Period p2 = p1.plus(Period.ofMonths(2));

System.out.println(“ The months after adding 2 months to 4 months is: “ + p2);

// calling the minus() method of Period class

Period p3 = p1.minus(Period.ofMonths(2));

System.out.println(“ The months after subtracting 2 months to 4 months is:” + p3);

}

}

Output:

In the output, there is a statement P2020Y8M24D. This means the period is 2020 year 8 months and 24 days. P6M and P2M define the period of 4 months and a period of 2 months.

11. java.time.ZoneId: java.time.ZoneId is a class present in the time package. This class is inherited by the object class, and it is implemented by a Serializable interface. In this class, we can identify the different time zones and print the difference between the instant time and local date time.

Example:

// program to implement the java.time.ZoneId class and display the current time zone and its id

import java.time.*;

import java.util.Locale;

import java.time.ZoneId;

import java.time.format.TextStyle;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“ Hello, World! “);

// creating the object to the LocalTime class and printing thecurrent time

LocalTime id = LocalTime.now();

System.out.println(“ The current time is: “ + id);

// creating the object to the ZoneId class and calling the of() method

ZoneId z1 = ZoneId.of(“Asia/Kolkata”);

ZoneId z2 = ZoneId.of(“Asia/Tokyo”);

// creating the object to the to the LOcalTime class and calling the now() object

LocalTime id1 = LocalTime.now(z1);

LocalTime id2 = LocalTime.now(z2);

System.out.println(“ The current id of the first time zone is: “ + id1);

System.out.println(“ The current id of the second time zone is: “ + id2);

System.out.println(“ Is the id of first time zone is before the id of the second time zone is:” + id1.isBefore(id2));

// creating the object to the ZoneId class and printing the current time zone

ZoneId z3 = ZoneId.systemDefault();

System.out.println(“ The current time zone is: “ + z3.getDisplayName(TextStyle.FULL, Locale.ROOT));

}

}

Output:

12. java.time.ZoneOffset: java.time.ZoneId is a class present in the time package. This class is used to describe the time zone. This class is inherited by the ZoneId class, and it is implemented by the Comparable interface.

In this class, we have mainly three constants.

1. Max: It is the maximum zone supported by the zone offset.

2. Min: It is the minimum zone supported by the zone offset.

3. UTC: It is the time zone offset constant for UTC.

Example:

// program to implement the java.time.ZoneOffset class and display the current date and time

import java.time.*;

import java.time.temporal.Temporal;

import java.time.ZoneOffset;

import java.time.temporal.ChronoField;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“ Hello, World! “);

// creating object to the ZoneOffset class

ZoneOffset z1 = ZoneOffset.UTC;

// creating an object to the Temporal class to print the current date, time and time zone

Temporal t = z1.adjustInto(ZonedDateTime.now());

System.out.println(“ The current date, time and time zone is: “ + t);

// creating object to the ZoneOffset class and calling the ofHours() method

ZoneOffset z2 = ZoneOffset.ofHours(5);

System.out.println(“ The Time in hours is: “ + z2);

// creating object to the ZoneOffset class and calling the ofHoursMintes() method

ZoneOffset z3 = ZoneOffset.ofHoursMinutes(5,30);

System.out.println(“ The time in hours and minutes is: “ + z3);

boolean b1 = z1.isSupported(ChronoField.OFFSET_SECONDS);

System.out.println(“ The current time supports the ChronoField.OFFSET_SECONDS or not: “ + b1);

boolean b2 = z1.isSupported(ChronoField.SECOND_OF_MINUTE);

System.out.println(“ The current time supports the ChronoField.SECOND_OF_MINUTE or not: “ + b2);

}

}

Output:

13. java.time.format.DateTimeFormatterBuilder: java.time.format.DateTimeFormatterBuilder is a class present in the time package, and With the help of this class, we can print the current date and time in the predefined formats or in our format.

Date and Time Formatting in Java

Date and time formatting is if we print the current date and time, the compiler will display the date and time in the default format to get the date and time in the desired format. We have to use date and time formatting.

Example:

// program to print the current date and time in different formats using SimpleDateFormat class

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Locale;

class HelloWorld {

public static void main(String[] args) {

System.out.println(“Hello, World!”);

// creating object to the date class

Date d = new Date();

SimpleDateFormat formatter = new SimpleDateFormat(“MM/dd/yyyy”);

// printing the date and time in different formats

// 1. printing date and time in MM/dd/yyyy date format

String str = formatter.format(d);

System.out.println(“ The Date and time Format with MM/dd/yyyy : “+str);

// 2. printing date and time in dd-M-yyyy hh:mm:ss format

formatter = new SimpleDateFormat(“dd-M-yyyy hh:mm:ss”);

str = formatter.format(d);

System.out.println(“ The Date and Format in dd-M-yyyy hh:mm:ss : “+str);

// 3. printing date and time in dd MMMM yyyy format

formatter = new SimpleDateFormat(“dd MMMM yyyy”);

str = formatter.format(d);

System.out.println(“ The Date and Time Format in dd MMMM yyyy : “+str);

// 4. printing the date and time in dd MMMM yyyy zzzz format

formatter = new SimpleDateFormat(“dd MMMM yyyy zzzz”);

str = formatter.format(d);

System.out.println(“ The Date and Format in dd MMMM yyyy zzzz : “+str);

// 5. printing the date and time in E, dd MMM yyyy HH:mm:ss z format

formatter = new SimpleDateFormat(“E, dd MMM yyyy HH:mm:ss z”);

str = formatter.format(d);

System.out.println(“ The Date and Time Format in E, dd MMM yyyy HH:mm:ss z : “+str);

}

}

Output:

Conclusion

In this article, we learned about the java date and time API’s. We learned about the APIs we are used in java to work on the date and time. We learned about the classical classes present in java.

We discussed the disadvantages of the classical API class. We discussed the methods to overcome the drawbacks of classical APIs. Next, we get into the date and time API in the java 8 version.

In the java 8 version, a separate package is defined for date and time. We discussed examples in each class present in the classical API. We discussed the advantages of the new API of the time package.

We collected all the classes present in the time package. We performed the examples on the classes of time packages. We performed how to format the date and time in the desired format.

--

--

Mahesh Sharma

Hey, I'm Mahesh Sharma, a passionate digital marketer with 10+ years of experience in the field. I'll be sharing topics such as SEO, SMO, PPC/ SEM.