Date and time java 8 API

There are several applications that are using date in java and time in java. But before java 8 date and time are very confusing topics with serval problems. Java 8 introduced a new feature that is known as date and time java 8 API.  In this post, we will see what the new features are introduced by Java 8.

Here is the table content of the article will we will cover this topic.
1. Why do we need new Java Date Time API?
2. Java 8 Date and time implementation?
3. Java 8 Date Time API Examples?
i) LocalDate
ii) LocalTime
iii) LocalDateTime
iv) Instant

4. How to check if given date on weekend or holiday with Java 8?

date and time java 8 API


Why do we need new Java Date Time API?

Before moving further to the Java 8 Date Time API, we need to know the problem area and why do we need a new API for this. Let’s discuss some problems that came before Java 8:

1. The Java Date Time classes are not defined consistently, there are two classes to get the date one presented in java.util and another is presented in java.sql packages. The date class of java.util package is human readable and the date class of java.sql packages is used to save in the database. Both classes have the same name, so it creates confusion. Another problem is formatting, and parsing classes are defined in java.text package.

2. The Date class of java.util package contains both date and time. So, when we get the only date its unnecessary to show the time also. Where the date class of java.sql contains the only date. It seems a bad API design because both the classes have the same name.

import java.util.Date;

class DateAndTime 
{
  public static void main(String[] args) 
  {
	  Date simpleDate = new Date();
	  System.out.println("Date and Time: "+ simpleDate);
  }
}

Output: Date and Time: Sun Sep 27 11:13:14 IST 2020

3. Another problem is formatting and parsing because for time, timestamp, formatting and parsing classes are not defined. We have java.text.DateFormat class for parsing and formatting those are again defined in different packages. . Usually SimpleDateFormat class is used for parsing and formatting.

import java.sql.Timestamp;
import java.util.Date;

class DateAndTime 
{
  public static void main(String[] args) 
  {
      Date date = new Date();
      System.out.println(new Timestamp(date.getTime()));
  }
}

Output: 2020-09-27 11:23:09.887

4. The biggest problem is thread safety. All the Date classes are not thread-safe because they are mutable.

5. The date class doesn’t provide internationalization, there is no time zone support. The java.util.Calendar and java.util.TimeZone classes were introduced but they have also problems

Java 8 Date and time implementation

1. Java 8 provides all the classes with thread safety. Because all classes in the new Date Time API are immutable

2.Java 8 has separated classes for date and time, TimeStamp, TimeZone etc . Now there is no confusion in human-readable date time and machine time

3. Now themethods and their purpose are clearly defined and perform the same action in all the classes.

4. All the new Date Time API classes have methods that can perform common tasks, like plus, minus, format, parsing, etc.

Java 8 Date Time API Examples

Java LocalDate

In java LocalDate class exists in java.time package and it is an immutable class. This class represents Date with the default format of yyyy-MM-dd.

1. We can get the current date by of now() method and it will return the current system date in yyyy-MM-dd format.

2. We can create an object of LocalDate by use of  input string.

3. We can get the date in a specific time zone by the use of now() method because the now method is overloaded. We can pass the zoneId and get the date. This class provides the same functionality as java.sql.Date.

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

class DateAndTime 
{
  public static void main(String[] args) 
  {
	  //Getting the Current Date
	  LocalDate today = LocalDate.now();
	  System.out.println("Current Date="+today);
			
	  //Creating an object of LocalDate by providing input arguments
	  LocalDate specifiedDate = LocalDate.of(2020, Month.APRIL, 30);
	  System.out.println("Specific Date="+specifiedDate);
			
	  //Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
	  LocalDate todayIndia = LocalDate.now(ZoneId.of("Asia/Kolkata"));
	  System.out.println("Current Date in IST="+todayIndia);

	  //Getting date from the base date i.e 01/01/1970
	  LocalDate dateFromBase = LocalDate.ofEpochDay(365);
	  System.out.println("365th day from base date= "+dateFromBase);
			
	  LocalDate hundredDay2020 = LocalDate.ofYearDay(2020, 100);
	  System.out.println("100th day of 2014="+hundredDay2020);
  }
}

Output: Current Date=2020-09-27
Specific Date=2020-04-30
Current Date in IST=2020-09-27
365th day from base date= 1971-01-01
100th day of 2014=2020-04-09

Java LocalTime

The LocalTime class is also defined in java.time package. It is an immutable class that is used to represents a time in the human-readable format. This class returns the hh:mm:ss.zzz format and it is the default format.

1. To get the current time we can use the now() method and it returns the current system time in hh:mm:ss.zzz format.

2. By use of input string we can create an instance of LocalTime class.

3. We can get the time according to the specific time zone. We can use the overloaded now() method.

import java.time.LocalTime;
import java.time.ZoneId;

class DateAndTime 
{
  public static void main(String[] args) 
  {
	  //Getting the Current Date
	  LocalTime today = LocalTime.now();
	  System.out.println("Current Date= "+today);
			
	  //Creating an object of LocalTime by providing input arguments
	  LocalTime specifiedTime = LocalTime.of(12,20,25,40);
	  System.out.println("Specific Time ="+specifiedTime);
			
	  //Current time in "Asia/Kolkata", you can get it from ZoneId javadoc
	  LocalTime todayIndia = LocalTime.now(ZoneId.of("Asia/Kolkata"));
	  System.out.println("Current Time in IST="+todayIndia);

	  //Getting date from the base date i.e 09/09/2020
      LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
	  System.out.println("10000th second time= "+specificSecondTime);
  }
}

Output: Current Date= 13:34:44.155766200
Specific Time =12:20:25.000000040
Current Time in IST=13:34:44.158305200
10000th second time= 02:46:40

java LocalDateTime

The java LocalDateTime class is an immutable class that is used to represent date and time. The default format of date and time is yyyy-MM-dd-HH-mm-ss.zzz. This has a factory method that takes LocalDate and LocalTime input arguments to create a LocalDateTime instance.

1. We can get the current date and time by use of the now() method and it returns the current system date and time in yyyy-MM-dd-HH-mm-ss.zzz format.  We can use the factory method to get Date and time by use of  LocalDate and LocalTime as input.

2. We can get the current Date and time by use of input string.

3. By use of specified time zone we can get the Date and time.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;

class DateAndTime 
{
  public static void main(String[] args) 
  {
	  //Get the Current Date and Time
	  LocalDateTime today = LocalDateTime.now();
	  System.out.println("Current DateTime="+today);
			
	  //Get the Current Date using LocalDate and LocalTime
	  today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
	  System.out.println("Current DateTime="+today);
			
	  //Creating LocalDateTime by providing input arguments
	  LocalDateTime specificDateTime = LocalDateTime.of(2020, Month.APRIL, 30, 10, 10, 30);
	  System.out.println("Specific Date="+specificDateTime);
			
	  LocalDateTime currentDateTime = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
	  System.out.println("Current Date and Time in IST="+currentDateTime);
	  
	  //Getting date from the base date i.e 01/01/1970
	  LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
	  System.out.println("10000th second time from 01/01/1970= "+dateFromBase);

	}

}

Output: Current DateTime=2020-09-27T13:54:43.410044500
Current DateTime=2020-09-27T13:54:43.412038100
Specific Date=2020-04-30T10:10:30
Current Date and Time in IST=2020-09-27T13:54:43.413043
10000th second time from 01/01/1970= 1970-01-01T02:46:40 

Java instant

The Instant class represents the machine-readable time format. It stores date and time in unix timestamp.

import java.time.Duration;
import java.time.Instant;

class DateAndTime 
{
  public static void main(String[] args) 
  {
	  //Get Current timestamp
	  Instant dateTimestamp = Instant.now();
	  System.out.println("Current Timestamp = "+dateTimestamp);
			
	  //Instant from timestamp
      Instant specificTime = Instant.ofEpochMilli(dateTimestamp.toEpochMilli());
	  System.out.println("Specific Time = "+specificTime);
			
	  //Duration example
	  Duration thirtyDay = Duration.ofDays(30);
	  System.out.println(thirtyDay);
	}
}

Output: Current Timestamp = 2020-09-27T08:50:09.393520200Z
Specific Time = 2020-09-27T08:50:09.393Z
PT720H

How to check if given date on weekend or holiday with Java 8?

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

public class Example
{
    public static void main(String args[])
    {
    	LocalDate specifiedDate = LocalDate.of(2020, Month.APRIL, 30);   
    	DayOfWeek day = specifiedDate.getDayOfWeek();   // gets the day of the week as integer

	    if (day.equals(DayOfWeek.SUNDAY)) 
	    {
	        System.out.println("It's a Sunday!");
	    }
	    else
	    	System.out.println("It's not a Sunday!");
    } 
}

Output: It’s not a Sunday!

Leave a Comment