New Date-Time API in Java 8
New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API :
- Not thread safe : Unlike old java.util.Date which is not thread safe the new date-time API is immutable and doesn’t have setter methods.
- Less operations : In old API there are only few date operations but the new API provides us with many date operations.
Java 8 under the package java.time introduced a new date-time API, most important classes among them are :
- Local : Simplified date-time API with no complexity of timezone handling.
- Zoned : Specialized date-time API to deal with various timezones.
- LocalDate/LocatTime and LocalDateTime API : Use it when time zones are NOT required.
// Java code for LocalDate// / LocalTime Functionimportjava.time.*;importjava.time.format.DateTimeFormatter;publicclassDate {publicstaticvoidLocalDateTimeApi(){// the current dateLocalDate date = LocalDate.now();System.out.println("the current date is "+date);// the current timeLocalTime time = LocalTime.now();System.out.println("the current time is "+time);// will give us the current time and dateLocalDateTime current = LocalDateTime.now();System.out.println("current date and time : "+current);// to print in a particular formatDateTimeFormatter 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 secondsMonth month = current.getMonth();intday = current.getDayOfMonth();intseconds = current.getSecond();System.out.println("Month : "+month+" day : "+day+" seconds : "+seconds);// printing some specified dateLocalDate 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);}// Driver codepublicstaticvoidmain(String[] args){LocalDateTimeApi();}}chevron_rightfilter_noneOutput:the current date is 2018-04-09 the current time is 06:21:10.409 current date and time : 2018-04-09T06:21:10.410 in foramatted manner 09-04-2018 06:21:10 Month : APRIL day : 9 seconds : 10 the repulic day :1950-01-26 specfic date with current time : 2016-04-24T06:21:10.410
- Zoned date-time API : Use it when time zones are to be considered
// Java code for Zoned date-time APIimportjava.time.LocalDateTime;importjava.time.ZoneId;importjava.time.ZonedDateTime;importjava.time.format.DateTimeFormatter;publicclassZone {// Function to get Zoned Date and TimepublicstaticvoidZonedTimeAndDate(){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 zoneZonedDateTime currentZone = ZonedDateTime.now();System.out.println("the current zone is "+currentZone.getZone());// getting time zone of specific place// we use withZoneSameInstant(): it is// used to return a copy of this date-time// with a different time-zone,// retaining the instant.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);}// Driver codepublicstaticvoidmain(String[] args){ZonedTimeAndDate();}}chevron_rightfilter_noneOutput:formatted current Date and Time : 09-04-2018 06:21:13 the current zone is Etc/UTC tokyo time zone is 2018-04-09T15:21:13.220+09:00[Asia/Tokyo] formatted tokyo time zone 09-04-2018 15:21:13
- Period and Duration classes :
Period : It deals with date based amount of time.
Duration : It deals with time based amount of time.
// Java code for period and durationimportjava.time.LocalDate;importjava.time.LocalTime;importjava.time.Month;importjava.time.Duration;importjava.time.Period;publicclassGeekforgeeks {publicstaticvoidcheckingPeriod(){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);}// Function to check durationpublicstaticvoidcheckingDuraion(){LocalTime time1 = LocalTime.now();System.out.println("the current time is "+time1);Duration fiveHours = Duration.ofHours(5);// adding five hours to the current// time and storing it in time2LocalTime 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);}// Driver codepublicstaticvoidmain(String[] args){checkingPeriod();checkingDuraion();}}chevron_rightfilter_noneOutput:gap between dates is a period of P3Y3M28D the current time is 06:21:18.248 after adding five hours of duration 11:21:18.248 duraion gap between time1 & time2 is PT-5H
- ChronoUnits Enum : java.time.temporal.ChronoUnit enum is added in Java 8 to replace integer values used in old API to represent day, month etc.
// Java code for ChronoUnits Enumimportjava.time.LocalDate;importjava.time.temporal.ChronoUnit;publicclassGeeksforgeeks {// Function to check ChronoUnitpublicstaticvoidcheckingChronoEnum(){LocalDate date = LocalDate.now();System.out.println("current date is :"+date);// adding 2 years to the current dateLocalDate year =date.plus(2, ChronoUnit.YEARS);System.out.println("next to next year is "+year);// adding 1 month to the current dataLocalDate nextMonth =date.plus(1, ChronoUnit.MONTHS);System.out.println("the next month is "+nextMonth);// adding 1 week to the current dateLocalDate nextWeek =date.plus(1, ChronoUnit.WEEKS);System.out.println("next week is "+ nextWeek);// adding 2 decades to the current dateLocalDate Decade =date.plus(2, ChronoUnit.DECADES);System.out.println("20 years after today "+Decade);}// Driver codepublicstaticvoidmain(String[] args) {checkingChronoEnum();}}chevron_rightfilter_noneOutput:current date is :2018-04-09 next to next year is 2020-04-09 the next month is 2018-05-09 next week is 2018-04-16 20 years after today 2038-04-09
- TemporalAdjuster : It is used to perform various date related operations.
// Java code Temporal Adjusterimportjava.time.LocalDate;importjava.time.temporal.TemporalAdjusters;importjava.time.DayOfWeek;publicclassGeek{// Function to check date and time// according to our requirementpublicstaticvoidcheckingAdjusters(){LocalDate date = LocalDate.now();System.out.println("the current date is "+date);// to get the first day of next monthLocalDate dayOfNextMonth =date.with(TemporalAdjusters.firstDayOfNextMonth());System.out.println("firstDayOfNextMonth : "+dayOfNextMonth );// get the next saturdayLocalDate nextSaturday =date.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));System.out.println("next satuday from now is "+nextSaturday);// first day of current monthLocalDate firstDay =date.with(TemporalAdjusters.firstDayOfMonth());System.out.println("firstDayOfMonth : "+firstDay);// last day of current monthLocalDate lastDay =date.with(TemporalAdjusters.lastDayOfMonth());System.out.println("lastDayOfMonth : "+lastDay);}// Driver codepublicstaticvoidmain(String[] args){checkingAdjusters();}}chevron_rightfilter_noneOutput:the current date is 2018-04-09 firstDayOfNextMonth : 2018-05-01 next satuday from now is 2018-04-14 firstDayOfMonth : 2018-04-01 lastDayOfMonth : 2018-04-30
Recommended Posts:
- PHP | Converting string to Date and DateTime
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java lang.Long.byteValue() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
- Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java 8 | ArrayDeque removeIf() method in Java with Examples
- Java.lang.Character.Subset Class in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



