Back to: Java Tutorials For Beginners and Professionals
Date and Time API in Java with Examples
In this article, I am going to discuss Date and Time API in Java with Examples. Please read our previous article where we discussed Reflection in Java. At the end of this article, you will understand the following pointers in detail.
- Date and Time API in Java
- Java LocalDate Time Class
- ZonedDate Time Class in Java
- Java Period Class
- Java Duration Class
- TemporalAdjuster in Java
Date and Time API in Java
A new date-time API is introduced in Java 8 under the package java.time. It is introduced to overcome the following drawbacks of old date-time API:
- Not thread-safe: Old java.util.Date is not thread-safe. To deal with this issue Java 8 introduced the new date-time API which is immutable and doesn’t have setter methods.
- Fewer operations: The new API provides us with many date operations, whereas in old API there are only a few date operations.
Important classes of Date-Time API are:
- Local: It is used to simplify the date-time API with no complexity of timezone handling.
- Zonal: It is a specialized date-time API to deal with various timezones.
Java LocalDate Time Class
It is an immutable date-time object that represents a date-time, with the default format as yyyy-MM-dd-HH-mm-ss.zzz. It is used when time zones are NOT required.
Declaration: public final class LocalDateTime extends Object implements Temporal, Temporal Adjuster, Serializable
Methods
- String format(DateTimeFormatter formatter): Used to perform this date-time using the specified formatter.
- int get(TemporalField field): Used to get the value of the specified field from this date-time as an int.
- LocalDateTime minusDays(long days): Used to return a copy of this LocalDateTime with the specified number of days subtracted.
- Static LoaclDateTimenow(): Used to obtain the current date-time from the system clock in the default time-zone.
- static LoaclDateTime of(LocalDate date, LocalTime time): Used to obtain an instance of LocalDateTime from a date and time.
- LocalDateTime plusDays(long days): Used to return a copy of this LocaldateTime with the specified number of days added.
- Boolean equals(Object obj): Used to check if this date-time is equal to another date-time.
Sample Program: LocalDateTime API
import java.time.*; import java.time.format.DateTimeFormatter; public class LocalDateTimeDemo { public static void LocalDateTimeApi () { // the current date LocalDate date = LocalDate.now (); System.out.println ("the current date is " + date); // the current time LocalTime time = LocalTime.now (); System.out.println ("the current time is " + time); // will give us the current time and date LocalDateTime current = LocalDateTime.now (); System.out.println ("current date and time : " + current); // to print in a particular format DateTimeFormatter format = DateTimeFormatter.ofPattern ("dd-MM-yyyy HH:mm:ss"); String formatedDateTime = current.format (format); System.out.println ("in foramatted manner " + formatedDateTime); // printing months days and seconds Month month = current.getMonth (); int day = current.getDayOfMonth (); int seconds = current.getSecond (); System.out.println ("Month : " + month + " day : " + day + " seconds : " + seconds); // printing some specified date LocalDate date2 = LocalDate.of (1950, 1, 26); System.out.println ("the repulic day :" + date2); // printing date with current time. LocalDateTime specificDate = current.withDayOfMonth (24).withYear (2016); System.out.println ("specfic date with " +"current time : " + specificDate); } public static void main (String[]args) { LocalDateTimeApi(); } }
Output
ZonedDate Time Class in Java
It is an immutable representation of a date-time with a time-zone. Use it when time zones are to be considered. It is used to store all date and time fields.
Declaration: public final class ZonedDateTime extends Object implements Temporal, Serializable
Methods
- String format(DateTimeFormatter formatter): Used to format this date-time using the specified formatter.
- int get(TemporatField field): Used to get the value of the specified field from this date-time as an int.
- ZonedId getZone(): Used to get the time-zone, such as ‘Asia/Kolkata’.
- ZonedDateTime withZoneSameInstant(ZoneId zone): Used to return a copy of this date-time with a different time-zone, retaining the instant.
- static ZonedDateTime now(): Used to obtain the current date-time from the system clock in the default time-zone.
- static ZonedDateTime of(LocalDate date, LocalTime time, ZonedId zone): Used to obtain an instance of ZonedDateTime from a local date and time.
- ZonedDateTime minus(long amountToSubtract, TemporalUnit unit): Used to return a copy of this date-time with the specified amount subtracted.
- ZonedDateTime plus(long amountToAdd, TemporalUnit unit): Used to return a copy of this date-time with the specified amount added.
Sample Program: ZonedDateTime API in Java
import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class ZonedDateTimeDemo { //Function to get Zoned Date and Time public static void ZonedTimeAndDate () { LocalDateTime date = LocalDateTime.now (); DateTimeFormatter format1 = DateTimeFormatter.ofPattern ("dd-MM-yyyy HH:mm:ss"); String formattedCurrentDate = date.format (format1); System.out.println ("formatted current Date and" +" Time : " + formattedCurrentDate); // to get the current zone ZonedDateTime currentZone = ZonedDateTime.now (); System.out.println ("the current zone is " + currentZone.getZone ()); ZoneId tokyo = ZoneId.of ("Asia/Tokyo"); ZonedDateTime tokyoZone = currentZone.withZoneSameInstant (tokyo); System.out.println ("tokyo time zone is " + tokyoZone); DateTimeFormatter format = DateTimeFormatter.ofPattern ("dd-MM-yyyy HH:mm:ss"); String formatedDateTime = tokyoZone.format (format); System.out.println ("formatted tokyo time zone " + formatedDateTime); } public static void main (String[]args) { ZonedTimeAndDate (); } }
Output
Java Period Class
It is used to measures time in years, months, and days. Deals with the date-based amount of time.
Declaration: public final class Period extends Object implements ChronoPeriod, Serializable
Methods:
- Temporal addTo(Temporal temporal): Used to add the period to the specified temporal object.
- long get(TemporalUnit unit): Used to get the value of the requested unit.
- int getYears(): Used to get the number of years of this period.
- boolean isZero(): Used to check if all three units of this period are zero.
- Period minus(TemporalAmount amountToSubtract): Used to return a copy of this period with the specified period subtracted.
- static Periodof(int years, int months, int days): Used to return a copy of this period with the specified period added.
Sample Program: Period API in Java
import java.time.LocalDate; import java.time.LocalTime; import java.time.Month; import java.time.Period; public class PeriodDemo { public static void checkingPeriod () { LocalDate date1 = LocalDate.now (); LocalDate date2 = LocalDate.of (2014, Month.DECEMBER, 12); Period gap = Period.between (date2, date1); System.out.println ("gap between dates " + "is a period of " + gap); } public static void main (String[]args) { checkingPeriod (); } }
Output: gap between dates is a period of P5Y8M14D
Java Duration Class
It is used to measures time in seconds and nanoseconds. Deals with a time-based amount of time.
Declaration: public final class Duration extends Object implements TemporalAmount, Serializable
Methods:
- Temporal addTo(Temporal temporal): Used to add this duration to the specified temporal object.
- Static Duration between(Temporal startInclusive, Temporal endExclusive): Used to obtain a Duration representing the duration between two temporal objects.
- long get(TemporalUnit unit): Used to get the value of the requested unit.
- boolean isNegative(): Used to check if this duration is negative, excluding zero.
- boolean isZero(): Used to check if this duration is zero length.
- Duration minus(Duration duration ): Used to return a copy of this duration with the specified duration subtracted.
- Duration plus(Duration duration): Used to return a copy of this duration with the specified duration added.
Sample Program: Duration API in Java
import java.time.LocalDate; import java.time.LocalTime; import java.time.Month; import java.time.Duration; public class DurationDemo { // Function to check duration public static void checkingDuraion () { LocalTime time1 = LocalTime.now (); System.out.println ("the current time is " + time1); Duration fiveHours = Duration.ofHours (5); LocalTime time2 = time1.plus (fiveHours); System.out.println ("after adding five hours " +"of duration " + time2); Duration gap = Duration.between (time2, time1); System.out.println ("duraion gap between time1" + " & time2 is " + gap); } public static void main (String[]args) { checkingDuraion (); } }
Output
TemporalAdjuster in Java
TemporalAdjuster is used to perform various date-related operations. This interface has a single abstract method named adjustInto() which can be called in any of its implementations by passing a Temporal object to it. It allows us to perform complex date manipulations.
Sample Program: TemporalAdjuster in Java
import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; import java.time.DayOfWeek; public class TemporalAdjusterDemo { public static void checkingAdjusters () { LocalDate date = LocalDate.now (); System.out.println ("the current date is " + date); // To get the first day of next month LocalDate dayOfNextMonth =date.with (TemporalAdjusters.firstDayOfNextMonth ()); System.out.println ("firstDayOfNextMonth : " + dayOfNextMonth); // get the next Saturday LocalDate nextSaturday = date.with (TemporalAdjusters.next (DayOfWeek.SATURDAY)); System.out.println ("next satuday from now is " + nextSaturday); // first day of the current month LocalDate firstDay = date.with (TemporalAdjusters.firstDayOfMonth ()); System.out.println ("firstDayOfMonth : " + firstDay); // last day of the current month LocalDate lastDay = date.with (TemporalAdjusters.lastDayOfMonth ()); System.out.println ("lastDayOfMonth : " + lastDay); } public static void main (String[]args) { checkingAdjusters (); } }
Output
In the next article, I am going to discuss Calendar Class in Java with Examples. Here, in this article, I try to explain the Date and Time API in Java with Examples. I hope you enjoy this Date and Time API in Java with Examples article.