$show=/label

Java 8 New Date Time API Examples

SHARE:

A quick guide to Java 8 Date Time api along with the practical examples. How to handle timezones for different countries.

1. Overview


In this java 8 programming tutorial, we will be learning today Date-Time api is introduced in java 8. Before that first, we will see what are the drawbacks of java.util.Date api before java 8. And next, features of new Date Time api. What are the new classes introduced? Working example programs on each class and how the dates are simplified using with timezones.

Java 8 New Date Time API Examples



2. Drawbacks of java.util.Date API


API java.util.Date drawbacks before java 8.

2.1 Not Thread Safe


Older version of Date api does not support for handling concurrent scenarios. So, It is not thread-safe. That means, developers need to handle multithreaded issues and have to write many lines of code in a consistent manner. The new api has introduced the support for thread-safe and more easy now to deal with the real-time concurrent scenarios.

2.2 Poor Desing and Lesser Operations


Old api has default values as Date starts from 1990, the month starts from 1 and day starts from 0. There is no uniformity here. And also old api provides fewer methods to do some operations whereas new api has come up with the various utility methods for such operations.

2.3 Difficulty in dealing with Timezone dates


I have a scenario in my career when I started my carrier. We were working with multiple clients, we need to show the times in their local timezones and found that this is not an easy job to do. But, we implemented somehow. Later some time, started seeing the differences when the daylight saving started. For this, we had to do some tweaks.
But, You are good to deal with timezones using Java 8 api and it made very simple. We will see the example programs on timezones.

3. New Java 8 Date API changes


As of now, We have seen the problems that we were facing before java. All are now addressed in new DateTime api. All new classes are placed under package java.time.

Below are the two base class types and this is a category type that classes start with their name. But, many popular websites are describing these two are classes in java and I have searched but could not find these Local and Zoned as a class or interface in Java 8 api.

A) Local
B) Zoned

3.1 Local classes


Local − Simplified date-time API classes with no complexity of timezone handling.

Local API classes.

LocalDate
LocalTime
LocalDateTime

All these classes are Immutable classes and have private constructors. So, directly objects can not be created and should use the now() or of() methods to create its instances.

3.2 Zoned classes


Zoned - Specialized date-time API to deal with various timezones.

The zoned type has the only implementation class.

ZonedDateTime

In addition to this, there is a new concept TemporalAdjuster, ChronoUnits, Period and Duration added in java 8.

4. New Date Time API Examples


Let us write a simple example program for these classes.

How to compare two dates in java 8 ?

4.1 LocalDate Example


A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03 and it is in package java.time.LocalDate.

This handles only date but not time.

package com.javaprogramto.w3schools.programs.java8.dateapi;

import java.time.LocalDate;
import java.time.Month;

public class LocalDateExample {

    public static void main(String[] args) {

        // Getting the current LocalDate object.
        LocalDate now = LocalDate.now();
        System.out.println("Present date : " + now);

        // getting year
        int year = now.getYear();

        // getting month
        Month month = now.getMonth();

        // getting day
        int day = now.getDayOfMonth();

        // printing all these three values.
        System.out.println("year : " + year + " , month : " + month + ", day : " + day);

        // getting month in int value
        int monthInt = now.getMonthValue();

        // printing in format YYYY-MM-DD
        System.out.println("today date : " + year + "-" + monthInt + "-" + day);

        LocalDate oldDate = LocalDate.of(2015, 2, 2);
        System.out.println("Old date : " + oldDate);
        
        

    }

}

Output:


Present date : 2019-12-26
year : 2019 , month : DECEMBER, day : 26
today date : 2019-12-26
Old date : 2015-02-02

4.2 LocalTime Example


A time without a time-zone in the ISO-8601 calendar system, such as 10:15:30.  This handles only with time and not with a date.

package com.javaprogramto.w3schools.programs.java8.dateapi;
/**
 * Java program to LocalTime class
 * 
 */

import java.time.LocalTime;

public class LocalTimeExample {

    public static void main(String[] args) {

        // Getting the curent LocalDate object.
        LocalTime now = LocalTime.now();
        System.out.println("Present time : " + now);

        // getting hour
        int hour = now.getHour();

        // getting minutes
        int minute = now.getMinute();

        // getting second
        int second = now.getSecond();

        // printing all these three values.
        System.out.println("Hour : " + hour + " , Minute : " + minute + ", Second : " + second);

        // getting nano seconds
        int nanoSec = now.getNano();

        // printing in format HH:24MM:ss:SSS
        System.out.println("time now in format : " + hour + ":" + minute + ":0" + second + ":" + nanoSec);

        LocalTime oldTime = LocalTime.of(13, 20, 25);
        System.out.println("Old time : " + oldTime);

    }

}

Output:

Present time : 15:12:15.181
Hour : 15 , Minute : 12, Second : 15
time now in format : 15:12:015:181000000
Old time : 13:20:25

4.3 LocalDateTime Example


A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.  This works with both date and time at a time.


package com.javaprogramto.w3schools.programs.java8.dateapi;

/**
 * 
 * Java program to LocalDateTime class and examples
 * 
 */
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;

public class LocalDateTimeExample {

    public static void main(String[] args) {

        // Getting the curent LocalDate object.
        LocalDateTime now = LocalDateTime.now();
        System.out.println("Present date : " + now);

        // getting year
        int year = now.getYear();

        // getting month
        Month month = now.getMonth();

        // getting day
        int day = now.getDayOfMonth();

        // getting hour
        int hour = now.getHour();

        // getting minutes
        int minute = now.getMinute();

        // getting second
        int second = now.getSecond();

        // printing all these three values.
        System.out.println("year : " + year + " , month : " + month + ", day : " + day + "Hour : " + hour
                + " , Minute : " + minute + ", Second : " + second);

        // creating the older date using of() method.
        LocalDateTime oldDate = LocalDateTime.of(1990, 12, 10, 10, 10, 10);
        System.out.println("Old date : " + oldDate);

        // Creating a new LocalDate instance using toLocalDate() method.
        LocalDate newlocalDate = now.toLocalDate();
        System.out.println("newlocalDate : " + newlocalDate);

        // Creating a new LocalTime instance using toLocalDate() method.
        LocalTime newlocalTime = now.toLocalTime();
        System.out.println("newlocalTime : " + newlocalTime);

        // Date parsing from string to date
        LocalDateTime strToDate = LocalDateTime.parse("2019-10-10T10:10:10");
        System.out.println("String to Date : " + strToDate);

    }

}

Output:


Present date : 2019-12-26T15:42:21.803
year : 2019 , month : DECEMBER, day : 26Hour : 15 , Minute : 42, Second : 21
Old date : 1990-12-10T10:10:10
newlocalDate : 2019-12-26
newlocalTime : 15:42:21.803
String to Date : 2019-10-10T10:10:10


4.4 ZonedDateTime Example


ZonedDateTime is used to work with timezones. If you are not working or not important to the timezones then you should use the LocalDateTime class.

A date-time with a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30+01:00 Europe/Paris. ZonedDateTime is an immutable object. Once it is created then its values can not be changed.
The ZoneId is an identifier used to represent different zones.

In this example, converting India time to Australia and Los_Angeles time zones.


package com.java.w3schools.blog.java.program.to.java8.datetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 
 * Java program to ZonedDateTime
 * 
 * @author JavaProgramTo.com
 *
 */
public class ZonedDateTimeExample {

 public static void main(String[] args) {

  LocalDateTime currentDateTime = LocalDateTime.now();

  System.out.println("India current DateTime : " + currentDateTime);

  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm:ss");

  ZonedDateTime zonedDateTime = currentDateTime.atZone(ZoneId.of("Australia/Sydney"));

  System.out.println("Aus Zoned time : " + formatter.format(zonedDateTime));

  ZoneId zoneId = zonedDateTime.getZone();
  System.out.println("zone id : " + zoneId);

  ZonedDateTime pstZoneTime = zonedDateTime.withZoneSameInstant(ZoneId.of("America/Los_Angeles"));
  System.out.println("PST time now : " + formatter.format(pstZoneTime));
 }

}

Output:


India current DateTime : 2019-12-27T00:29:06.803908
Aus Zoned time : 27 Dec 2019 00:29:06
zone id : Australia/Sydney
PST time now : 26 Dec 2019 05:29:06

4.5 TemporalAdjusters Example


TemporalAdjusters is a utility class to provide the support for date-time api.

package com.java.w3schools.blog.java.program.to.java8.datetime;

import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;

/**
 * 
 * TemporalAdjuster example
 * 
 * @author JavaProgramTo.com
 *
 */
public class TemporalAdjusterExample {

 public static void main(String[] args) {

  LocalDate localDate = LocalDate.now();

  System.out.println("Current Date : " + localDate);

  // get first day of the month
  LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
  System.out.println("firstDayOfMonth : " + firstDayOfMonth);

  // get first day of next month
  LocalDate firstDayOfNextMonth = localDate.with(TemporalAdjusters.firstDayOfNextMonth());
  System.out.println("firstDayOfNextMonth : " + firstDayOfNextMonth);

  // first day of the year
  LocalDate firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear());
  System.out.println("firstDayOfYear : " + firstDayOfYear);

 }

}

Output:

Current Date : 2019-12-27
firstDayOfMonth : 2019-12-01
firstDayOfNextMonth : 2020-01-01
firstDayOfYear : 2019-01-01

4.6 ChronoUnits, Period and Duration Examples


ChronoUnit is an enum under package java.time.temporal and used to represent the constants in the old api.
Period class is used to get the differences between the two dates. This deals with only day, year and month.
Duration class is used to deal with seconds and nanoseconds


import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.temporal.ChronoUnit;

public class ChronoUnitsPeriodDurationExample {

 public static void main(String[] args) {

  LocalDate now = LocalDate.now();
  System.out.println("Present time : " + now);

  // ChronoUnit examples

  LocalDate plus10days = now.plus(10, ChronoUnit.DAYS);
  System.out.println("adding 10 days : " + plus10days);

  LocalDate plus10months = now.plus(10, ChronoUnit.MONTHS);
  System.out.println("adding 10 months : " + plus10months);

  // Period example
  LocalDate octDate = LocalDate.of(2019, 12, 1);
  System.out.println("Oct date : " + octDate);

  int months = Period.between(octDate, now).getMonths();
  System.out.println("Months difference : " + months);

  int days = Period.between(octDate, now).getDays();
  System.out.println("days difference : " + days);

  // Duration example

  LocalTime timenow = LocalTime.of(10, 10, 0);
  LocalTime yesterdayTime = LocalTime.of(10, 10, 10);

  long seconds = Duration.between(timenow, yesterdayTime).getSeconds();
  System.out.println("seconds : " + seconds);
 }

}
 
Output:

Present time : 2019-12-27
adding 10 days : 2020-01-06
adding 10 months : 2020-10-27
Oct date : 2019-12-01
Months difference : 0
days difference : 26
seconds : 10

5. Conclusion


In this article, We have seen all new java 8 date time package, new classes, along with the example programs.

Examples on Date time api




COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 New Date Time API Examples
Java 8 New Date Time API Examples
A quick guide to Java 8 Date Time api along with the practical examples. How to handle timezones for different countries.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4PPTulcNEyHD13D1tgiBJriwJXx3_NhSAfix8FAmQjH3aBz6UFv7CChjXa7_xzNTydCnj21lZ0Ge7XxaEaNPR1MP91gycOvAHgPfRs6Z8J0YnhEetH3CppSl2MgWA0dE7wuU9Pww9sfA/s640/Java+8+New+Date+Time+API+Examples.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4PPTulcNEyHD13D1tgiBJriwJXx3_NhSAfix8FAmQjH3aBz6UFv7CChjXa7_xzNTydCnj21lZ0Ge7XxaEaNPR1MP91gycOvAHgPfRs6Z8J0YnhEetH3CppSl2MgWA0dE7wuU9Pww9sfA/s72-c/Java+8+New+Date+Time+API+Examples.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/12/java-8-new-date-time-api-examples.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/12/java-8-new-date-time-api-examples.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content