java8 - java.time.instant class tutorial with examples
In this tutorial, You are about java.time.Instant example and how to convert to a different time and date classes in java 8.
What is instant in java?
instant
is a class defined in java.time package.
It represents date
and time
in a timeline with correct nanoseconds
precision. Whereas 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 is stored in two fields. As part of the Initialization of Instant, Constructor also takes two fields. Instant(long epochSecond, int Nanos)
- Long epochSecond value: Number of seconds since standard epoch time
- Integer Nanos value: Number of nanoseconds from last seconds. This value is between 0 to 999,999,999.
It stores bigger long values where Java.util.Date
stores long value since many milliseconds since epoch time.
Instant Class Examples
Here is the instant class object hierarchy
public final class Instant
extends Object
implements Temporal, TemporalAdjuster, Comparable, Serializable
The instant class is immutable and thread-safe.
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 defined in java.util.Date
class, and used to convert from java.time.instant to Date object.
import java.time.Instant;
import java.util.Date;
public class ConvertInstantToDate {
public static void main(String[] args) {
Instant instant=Instant.now();
Date date = Date.from(instant);
System.out.println(instant);
System.out.println(date);
}
}
Output:
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 to support for Nanoseconds.
import java.time.Instant;
import java.util.Date;
public class ConvertDateToInstant {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
Instant instant = date.toInstant();
System.out.println(instant);
}
}
Output
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 an instant timezone.
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
public class InstantEqualCheck {
public static void main(String[] args) {
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:
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
.
import java.time.*;
import java.util.TimeZone;
public class ConvertLocalDateTimeToInstant {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2021, Month.AUGUST, 25, 13, 39);
Instant instant= ZonedDateTime.of(localDateTime, TimeZone.getTimeZone("EST").toZoneId()).toInstant();
System.out.println(instant);
}
}
Output:
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 different purposes.
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
public class ConvertInstantToLocalTime {
public static void main(String[] args) {
Instant instant = Instant.now();
LocalTime local = LocalTime.from(instant.atZone(ZoneId.of("GMT+3")));
System.out.println(instant);
System.out.println(local);
}
}
Output:
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.
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class ConvertInstantToString {
public static void main(String[] args) {
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:
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 objects in java8?
plus() method is used to return a new instance after adding a specific time. minus() method is used to return a new instance after subtracting a specific time
import java.time.Duration;
import java.time.Instant;
public class AddSubtractHoursToInstant {
public static void main(String[] args) {
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("Subtract One Day " + instant.minus(Duration.ofDays(1)));
System.out.println("Subtract 5 hours " + instant.minus(Duration.ofHours(5)));
System.out.println("Substrat 50 minutes" + instant.minus(Duration.ofMinutes(50)));
}
}
Output:
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
Subtract One Day 2018-08-26T16:51:59.328782200Z
Subtract 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.
import java.time.Instant;
import java.time.temporal.ChronoUnit;
public class InstantSupportedExample {
public static void main(String[] args) {
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:
2018-08-27T16:57:13.606815900Z
true
false
false
Conclusion
Finally, In this tutorial, You learned java.time.Instant class in java8 and multiple examples using this class