close
The Wayback Machine - https://web.archive.org/web/20241007051710/https://www.geeksforgeeks.org/new-date-time-api-java8/
Open In App

New Date-Time API in Java 8

Last Updated : 06 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

New date-time API is introduced in Java 8 to overcome the following drawbacks of old date-time API : 

  1. 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.
  2. 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 :  

  1. Local : Simplified date-time API with no complexity of timezone handling.
  2. Zoned : Specialized date-time API to deal with various timezones.
  • LocalDate/LocalTime and LocalDateTime API : Use it when time zones are NOT required.

Java




// Java code for LocalDate
// / LocalTime Function
import java.time.*;
import java.time.format.DateTimeFormatter;
  
public class Date {
 
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 formatted 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 republic day :"+date2);
  
    // printing date with current time.
    LocalDateTime specificDate =
        current.withDayOfMonth(24).withYear(2016);
 
    System.out.println("specific date with "+
                       "current time : "+specificDate);
}
 
    // Driver code
    public static void main(String[] args)
    {
        LocalDateTimeApi();
    }
}


Output

the current date is 2021-09-23
the current time is 20:52:39.954238
current date and time : 2021-09-23T20:52:39.956909
in formatted manner 23-09-2021 20:52:39
Month : SEPTEMBER day : 23 seconds : 39
the republic day :1950-01-26
specific date with current time : 2016-09-24T20:52:39.956909
  • Zoned date-time API : Use it when time zones are to be considered

Java




// Java code for Zoned date-time API
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
 
public class Zone {
 
// 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());
 
    // 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 code
    public static void main(String[] args)
    {
         
        ZonedTimeAndDate();
         
    }
}


Output: 

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




// Java code for period and duration
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.Duration;
import java.time.Period;
 
public class Geekforgeeks {
 
    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);
}
 
    // Function to check duration
    public static void checkingDuration()
    { 
 
        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 time2
        LocalTime time2 = time1.plus(fiveHours);
 
        System.out.println("after adding five hours " +
                           "of duration " + time2);
 
        Duration gap = Duration.between(time2, time1);
        System.out.println("duration gap between time1" +
                           " & time2 is " + gap);
}
 
    // Driver code
    public static void main(String[] args)
    {
        checkingPeriod();
        checkingDuration();
    }
}


Output

gap between dates is a period of P6Y6M25D
the current time is 18:34:24.813548
after adding five hours of duration 23:34:24.813548
duration 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




// Java code for ChronoUnits Enum
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
 
public class Geeksforgeeks {
 
    // Function to check ChronoUnit
    public static void checkingChronoEnum()
    {
        LocalDate date = LocalDate.now();
        System.out.println("current date is :" +
                            date);
     
        // adding 2 years to the current date
        LocalDate year =
             date.plus(2, ChronoUnit.YEARS);
         
        System.out.println("next to next year is " +
                            year);
             
        // adding 1 month to the current date
        LocalDate nextMonth =
                  date.plus(1, ChronoUnit.MONTHS);
         
        System.out.println("the next month is " +
                            nextMonth);
     
        // adding 1 week to the current date
        LocalDate nextWeek =
                  date.plus(1, ChronoUnit.WEEKS);
         
        System.out.println("next week is " + nextWeek);
     
        // adding 2 decades to the current date
        LocalDate Decade =
                  date.plus(2, ChronoUnit.DECADES);
                   
        System.out.println("20 years after today " +
                            Decade);
    }
     
    // Driver code
    public static void main(String[] args) {
     
        checkingChronoEnum();
         
    }
}


Output: 

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




// Java code Temporal Adjuster
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;
 
public class Geek
{
 
    // Function to check date and time
    // according to our requirement
    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 saturday from now is "+
                            nextSaturday);
 
        // first day of current month
        LocalDate firstDay =
                  date.with(TemporalAdjusters.
                  firstDayOfMonth());
                                    
        System.out.println("firstDayOfMonth : " +
                            firstDay);
 
        // last day of current month    
        LocalDate lastDay =
                  date.with(TemporalAdjusters.
                            lastDayOfMonth());
         
        System.out.println("lastDayOfMonth : " +
                            lastDay);
}
     
    // Driver code
    public static void main(String[] args)
    {
 
        checkingAdjusters();
    }
}


Output

the current date is 2021-07-09
firstDayOfNextMonth : 2021-08-01
next saturday from now is 2021-07-10
firstDayOfMonth : 2021-07-01
lastDayOfMonth : 2021-07-31

 



Previous Article
Next Article

Similar Reads

Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
LocalDateTime of(date, time) method in Java with Examples
The of(LocalDate date, LocalTime time) method of LocalDateTime class in Java is used to obtain an instance of LocalDateTime using the two input parameters, date and time. Initially, two separate instances are created. One is of LocalDate type and the other one is of LocalTime type. Then these are merged to create a LocalDateTime. Syntax: public sta
2 min read
Java - Current Date and Time
In software development, we often work with dates and times. To accurately capture the current date and time is fundamental for various applications, such as scheduling tasks, tracking events, etc. In Java, there is a built-in class known as the Date class and we can import java.time package to work with date and time API. Here we are supposed to p
4 min read
Android - Create a New Playlist in Your Spotify Account using Spotify Web API
Spotify is one of the world's most popular music streaming platforms, and it has a vast collection of songs, albums, playlists, and podcasts. With the Spotify Web API, developers can create amazing applications that interact with the Spotify service. Using the Web API's endpoints, one can get detailed metadata about artists, albums, and tracks dire
13 min read
Java JDK 21: New Features of Java 21
Hey, Java enthusiasts and learners! Java is the most trending language in the world, which attracts the population or you can say Java techies towards its simplicity and its super features with vast functionalities. So to make the development more interesting for Java developers, Java is again here with its evolving new features and functionalities
11 min read
Difference between Compile-time and Run-time Polymorphism in Java
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. In this article, we will see the difference between two types of polymorphisms, compile time and run time. Compile Time Polymorphism: Whenever an object is bound with its functionality at the
3 min read
How to Get Current Time and Date in Android?
Many times in android applications we have to capture the current date and time within our android application so that we can update our date according to that. In this article, we will take a look at How to get the current Time and Date in our android application. Note: This Android article covered in both Java and Kotlin languages. Step by Step I
3 min read
How to Convert String to Date Time in Scala?
In this article, we will learn how to convert String to DateTime in Scala. Converting String to DateTime consists of parsing a textual representation of date and time into a structured DateTime object for further manipulation and processing in Scala programs. Table of Content Using SimpleDateFormatUsing SimpleDateFormat with CalenderUsing Simple Pa
4 min read
Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API
Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. In this article, we are going to see about a REST API call to find the coordinates for the given latitude and longitude. Each and every area
6 min read
Java Deprecated API Scanner tool (jdepscan) in Java 9 with Examples
Java Deprecated API Scanner tool: Java Deprecated API Scanner tool i.e. jdeprscan is a static analyzing command-line tool which is introduced in JDK 9 for find out the uses of deprecated API in the given input. Here the input can be .class file name, directory or JAR file. Whenever we provide any input to jdeprscan command line tool then it generat
2 min read
New Features of Java 12
Oracle released Java SE(Standard Edition) 12 on March 19, 2019, after which they plan to have a new release every six months. JDK 12 came with a lot of improvements over JDK 11. This latest version offers a list of new features such as Switch Expressions, Default CDS Archives, Shenandoah, Microbenchmark Suite, among others. These new features are d
7 min read
JDK 17 - New Features in Java 17
Java 17 LTS is the latest long-term support release for the Java SE platform. JDK 17 binaries are free to use in production and free to redistribute, at no cost, under the Oracle No-Fee Terms and Conditions License, where LTS stands for long-term support. It was released on September 15, 2021. Have you ever wondered What do we mean by this? Without
7 min read
What's New in Java 15 and C++ 20?
Java 15, includes several new features and enhancements. Some notable new methods in Java 15 include: Hidden Classes This feature allows classes to be defined as hidden, which means they are not visible to code outside of the package in which they are defined. This can be used to improve the security and maintainability of code. It is mainly used f
8 min read
New macOS Rendering Pipeline in Java
The macOS rendering pipeline in Java refers to the process of rendering graphics on the screen of a macOS computer using the Java programming language. The macOS operating system provides a powerful graphics rendering engine called Quartz that is used by Java to render graphics on the screen. The rendering pipeline in Java involves several stages,
2 min read
new Operator vs newInstance() Method in Java
In Java, new is an operator where newInstance() is a method where both are used for object creation. If we know the type of object to be created then we can use a new operator but if we do not know the type of object to be created in beginning and is passed at runtime, in that case, the newInstance() method is used.In general, the new operator is u
3 min read
new operator in Java
When you are declaring a class in java, you are just creating a new data type. A class provides the blueprint for objects. You can create an object from a class. However obtaining objects of a class is a two-step process : Declaration : First, you must declare a variable of the class type. This variable does not define an object. Instead, it is sim
5 min read
JDK 23: New Features of Java 23
Java Development Kit (JDK) 23 is a long-awaited release, which brings numerous new features, enhancements and updates to increase performance, security and the overall experience of developers. This guide wants to provide an extensive review of what will be in JDK 23 such as new characteristics, necessary additions, upgrades from JDK 22 and the cur
14 min read
JDK 22: New Features of Java 22
JDK 22 release has been much awaited by the Java landscape which continues to witness modifications. The latest installation of JDK has more than enough technical improvements aimed at giving developers more control, simplifying development processes, and developing brand-new paradigms for high-performance Java application creation. With this artic
12 min read
java.time.Clock Class in Java
Java Clock class is present in java.time package. It was introduced in Java 8 and provides access to current instant, date, and time using a time zone. The use of the Clock class is not mandatory because all date-time classes also have a now() method that uses the system clock in the default time zone. The main purpose of using Clock class is to pl
3 min read
java.time.Year Class in Java
The java.time.Year class represents a year in the ISO-8601 calendar system, such as 2021. Year is an immutable date-time object that represents a year. This class does not store or represent a month, day, time, or time-zone. The years represented by this class follow the proleptic numbering system that is as follows: The year 0 is preceded by year
8 min read
java.time.format.DecimalStyle Class in Java
java.time.format.DecimalStyle class acts as a central point for accessing the information. A significant part of handling dates and times is that localization. This class provides localized decimal style utilized in date and time formatting. Clone, finalize, getClass, notify, notifyAll, wait, are the methods that are declared in this class. Syntax:
2 min read
java.time.OffsetDateTime Class in Java
Java is the most popular programming language and widely used programming language. Java is used in all kind of application like mobile application, desktop application, web application. In this Java java.time.OffsetDate, Time class is imported which is an immutable representation of a date-time with an offset. This class stores all date and time f
4 min read
java.time.ZoneOffset Class in Java
A time-zone offset is that the amount of your time that a time-zone differs from Greenwich/UTC. This is often usually a hard and fast number of hours and minutes. From the time package of java, ZoneOffset class is employed to represent the fixed zone offset from UTC zone and inherits the ZoneId class and implements the Comparable interface. public
3 min read
java.time.ZoneId Class in Java
A ZoneId is used to identify the rules that used to convert between a LocalDateTime and an Instant of time. The actual rules, describing when and the way the offset changes, are defined by ZoneRules. This class is just an ID wont to obtain the underlying rules. The given approach has opted because the government defines the rules and alters frequen
3 min read
java.time.YearMonth Class in Java
Java YearMonth class provides the output of the format "year-month". This class is an immutable class which means that it defines objects which, once created, never change their value. Any field which will be derived from a year and month, like quarter-of-year, are often obtained. This class does not store or represent a day, time or time-zone. For
4 min read
java.time.LocalDate Class in Java
Java is the most popular programming language and widely used programming language. Java is used in all kind of application like as mobile application, desktop application, web application. In this Java java.time.LocalDate class is imported which represents to display the current date. java.time: It is the package used to work with the current date
4 min read
java.time.temporal.TemporalAdjusters Class in Java
TemporalAdjusters Class in Java provides Adjusters, which are a key tool for modifying temporal objects. Examples include an adjuster that sets the date like “Second Saturday of the Month” or “Next Tuesday”, or one that sets the date to the last day of the month. TemporalAdjuster can be used in two ways. The first is by invoking the method on the i
4 min read
java.time.Instant Class in Java
In Java language, the Instant Class is used to represent the specific time instant on the current timeline. The Instant Class extends the Object Class and implements the Comparable interface. Declaration of the Instant Class public final class Instant extends Object implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable Fiel
4 min read
java.time.Period Class in Java
The Period Class in Java class obtains a quantity or amount of time in terms of years, months and days. The time obtained is a date-based amount of time in the ISO-8601 calendar system, such as '4 years, 5 months, and 6 days. The units which are supported for a period are YEARS, MONTHS, and days. All these three fields are always present but may be
5 min read
java.time.Duration Class in Java
Duration is the value-based Class present in the Java time library. It's used to get time-based amount of time. This class is immutable and thread-safe. This article describes all the methods present in this class and some basic examples using class methods. This class implements Serializable, Comparable<Duration>, TemporalAmount interfaces.
4 min read
Practice Tags :