Monday, August 27, 2018

java8 - java.time.instant class tutorial with examples

java.time.instant tutorials

instant is a class defined in java.time package. It represents date and time in a timeline with correct nanoseconds precision. Java.util.Date represents date and time in milliseconds precision.
Instant stores nanoseconds, so it requires more storage as it stores a number larger than long. Internally it stores in two fields. As part of Initialization of Instant, Constructor also two fields.
Instant(long epochSecond, int Nanos)
1. Long epochSecond value  - Number of seconds since standard epoch time
2. Integer Nanos value -  Number of nanoseconds from last seconds. This value is in between 0 to 999,999,999
It stores bigger long values where Java.util.Date stores long value since a number of milliseconds since epoch time.

Instant Class Signature

public final class Instant
   extends Object
      implements Temporal, TemporalAdjuster, Comparable, Serializable
The instant class is immutable and thread-safe.

Instant Class Examples 

Following is a list of examples about the usage and how to convert to different classes.

How to convert java.time.instant to java.util.Date in java8?

instant gives time in nanoseconds precision and Date gives milliseconds precision. Instant is more accurate than Date. We need to learn how to convert instant to Date in java8. from() is a static method in java.util.Date class used to convert from java.time.instant to Date object.
Instant instant=Instant.now();
    Date date = Date.from(instant);
    System.out.println(instant);
    System.out.println(date);
Output is
2018-08-27T16:04:13.627331100Z
Mon Aug 27 21:34:13 IST 2018

How to convert java.util.Date to java.time.instant in java8?

Instant is a new class introduced in java8. There are cases where we need to convert from Date to Instant. Date class has not support for Nanoseconds.
Date date = new Date();
System.out.println(date);
Instant instant = date.toInstant();
System.out.println(instant);
Output is

Mon Aug 27 21:39:35 IST 2018
2018-08-27T16:09:35.429Z

How to check if two instant dates are equal in java8?

The instant class will not work with the humanly readable year, month and day units for equality check. To make equality work, You need to first convert to LocalDate or LocalDateTime or ZonedDateTime with instant timezone.
Instant instantTime1 = Instant.now();
Instant instantTime2 = Instant.now().plus(5, ChronoUnit.HOURS);
Instant instantTime3 = Instant.now().plus(5, ChronoUnit.HOURS);
LocalDate ld1 = LocalDateTime.ofInstant(instantTime1, ZoneId.systemDefault()).toLocalDate();
LocalDate ld2 = LocalDateTime.ofInstant(instantTime2, ZoneId.systemDefault()).toLocalDate();
LocalDate ld3 = LocalDateTime.ofInstant(instantTime3, ZoneId.systemDefault()).toLocalDate();
System.out.println(ld1.isEqual(ld2));
System.out.println(ld2.isEqual(ld3));
Output is
false
true

How to convert LocalDateTime to Instant in java8?

LocalDateTime class holds Date, time and Timezone information. Create Instant object using ZonedDateTime.of() method by passing Zone information and LocalDateTime.
LocalDateTime localDateTime = LocalDateTime.of(2018, Month.AUGUST, 25, 13, 39);
  Instant instant=ZonedDateTime.of(localDateTime, TimeZone.getTimeZone("EST").toZoneId()).toInstant();
  System.out.println(instant); 
Output is
2018-08-25T18:39:00Z

How to Convert Instant to LocalTime object in java8?

LocalTime is a class to represent time without time zone in ISO-8601 format. LocalTime and Instant are introduced for a different purpose.
Instant instant = Instant.now();
LocalTime local =  LocalTime.from(instant.atZone(ZoneId.of("GMT+3")));
System.out.println(instant); 
System.out.println(local); 
Output is
2018-08-27T16:30:35.123741700Z
19:30:35.123741700

How to Convert Instant to a String object in java8? 

DateTimeFormatter object is created with the format and default timezone. Call format() method to convert to String.
Instant instant = Instant.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_INSTANT
             .withZone(ZoneId.systemDefault());
     DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
             .withZone(ZoneId.systemDefault());
     DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("MMM dd,yyyy HH:mm:ss")
             .withZone(ZoneId.systemDefault());
  System.out.println(instant); 
     System.out.println(dateTimeFormatter.format(instant));
     System.out.println(dateTimeFormatter1.format(instant));
     System.out.println(dateTimeFormatter2.format(instant));
Output is
 
  2018-08-27T16:42:35.853060600Z
2018-08-27T16:42:35.853060600Z
2018-08-27 22:12:35
Aug 27,2018 22:12:35

How to add or subtract days, Hours, secs Instant object in java8? 

plus() method is used to return new instance after adding a specific time.
minus() method is used to return new instance after subtracting specific time
 Instant instant = Instant.now();
System.out.println(instant);
System.out.println("Add One Day " + instant.plus(Duration.ofDays(1)));
System.out.println("Add 5 hours " + instant.plus(Duration.ofHours(5)));
System.out.println("Add 50 minutes" + instant.plus(Duration.ofMinutes(50)));
System.out.println("Substract One Day " + instant.minus(Duration.ofDays(1)));
System.out.println("Substract 5 hours " + instant.minus(Duration.ofHours(5)));
System.out.println("Substrat 50 minutes" + instant.minus(Duration.ofMinutes(50)));
Output is
 
2018-08-27T16:51:59.328782200Z
Add One Day 2018-08-28T16:51:59.328782200Z
Add 5 hours 2018-08-27T21:51:59.328782200Z
Add 50 minutes2018-08-27T17:41:59.328782200Z
Substract One Day 2018-08-26T16:51:59.328782200Z
Substract 5 hours 2018-08-27T11:51:59.328782200Z
Substrat 50 minutes2018-08-27T16:01:59.328782200Z

Instant isSupported() method example 

isSupported() checks whether the field is supported or not.
Instant instant = Instant.now();
System.out.println(instant);
System.out.println(instant.isSupported(ChronoUnit.DAYS));  
System.out.println(instant.isSupported(ChronoUnit.YEARS));      
System.out.println(instant.isSupported(ChronoUnit.WEEKS));      
Output is
2018-08-27T16:57:13.606815900Z
true
false
false

Related article


EmoticonEmoticon