In this article, we will discuss about newly introduced Instant class in Java 1.8 version for dealing with date/time information in program with ease and convenience which captures instantaneous moment in UTC/GMT or in other words current date/time in UTC/GMT
Prior to introducing LocalDate, LocalTime, LocalDateTime, ZonedDateTime, OffsetDateTime and Instant under java.time.*; package in Java 1.8 version, we have to deal with java.util.Date, java.util.Calendar, java.sql.Timestamp, java.sql.Time, java.util.TimeZone, System.currentTimeMillis() for date/time handling along with Offset/Zone in Java which isn’t easy & straight-forward and there are few issues as mentioned below,
- Thread-safety :- Existing Date/Time classes and its methods aren’t thread-safe and hence it’s not convenient to handle in concurrent/parallel environment
- Not so-easy API design :- Existing Date/Time classes’ methods aren’t convenient to use in day-to-day programmer’s coding or development
- Time-zone settings :- Developers or Programmer’s life becomes difficult while dealing with time zone settings in programs
Let’s move forward and discuss about java.time.Instant introduced in Java 1.8 version
1. ZonedDateTime v/s OffsetDateTime v/s Instant v/s LocalDateTime:
Before moving forward to detail out about Instant, let’s understand what are the difference between LocalDateTime & Instant & OffsetDateTime & ZonedDateTime
- LocalDateTime provides date/time without Offset/Zone information in the below format,
- yyyy-MM-ddTHH:mm:ss.nnn
- For example, 2022-06-29T17:31:25.387081200
- Instant provides/captures instantaneous moment or current date/time in UTC/GMT in the below format,
- yyyy-MM-ddTHH:mm:ss.nnnZ
- Where Z indicates zero or +00:00 or GMT/UTC time
- For example, 2022-06-29T12:01:25.369081700Z
- Note:- Instant date/time are time-zone unaware and it always returns current date/time at UTC/GMT
- OffsetDateTime provides date/time with Offset but no Zone information in the below format,
- yyyy-MM-ddTHH:mm:ss.nnn+HH:mm
- So, OffsetDateTime is LocalDateTime plus Offset from GMT/UTC information
- For example 2022-06-29T17:31:25.369081700+05:30
- ZonedDateTime provides date/time with Offset from GMT/UTC & ZoneId information in the below format,
- yyyy-MM-ddTHH:mm:ss.nnn+HH:mm[region/city]
- So, ZonedDateTime is OffsetDateTime plus ZoneId information in Square-brackets,
- For example 2022-06-29T17:31:25.368081700+05:30[Asia/Calcutta]
- In the below illustration, we are printing ZonedDateTime, OffsetDateTime, Instant & LocalDateTime twice
- First in the system default zone (i.e., Asia/Calcutta)
- Second, after providing ZoneId or Clock (Asia/Dubai) as argument to overloaded now() method
- ZonedDateTime, OffsetDateTime, Instant & LocalDateTime prints current date/time in their specific Zone except Instant
- LocalDateTime provides date/time to nano-second precision
- Instant provides date/time to nano-second precision in GMT/UTC
- OffsetDateTime provides date/time to nano-second precision and Offset from GMT/UTC information
- ZonedDateTime provides date/time to nano-second precision and Offset from GMT/UTC & ZoneId information
- Note: Time-difference from Greenwich Mean Time (GMT) or Universal Time Coordinated (UTC) is known as Offset
InstantVsOffsetVsZonedVsLocalDateTime.java
package in.bench.resources.instant;
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class InstantVsOffsetVsZonedVsLocalDateTime {
public static void main(String[] args) {
// 1. ZonedDateTime, OffsetDateTime, Instant and LocalDateTime in system default zone
System.out.println("1. ZonedDateTime, OffsetDateTime, Instant and LocalDateTime "
+ "in system default zone - [" + ZoneId.systemDefault() + "]");
// 1.1 ZonedDateTime - current date/time in default zone
ZonedDateTime zonedDateTime = ZonedDateTime.now();
System.out.println("\n1.1 ZonedDateTime :- \t" + zonedDateTime);
// 1.2 OffsetDateTime - current date/time in default zone
OffsetDateTime offsetDateTime = OffsetDateTime.now();
System.out.println("1.2 OffsetDateTime :- \t" + offsetDateTime);
// 1.3 Instant - current date/time in GMT/UTC
Instant instant = Instant.now();
System.out.println("1.3 Instant :- \t\t" + instant);
// 1.4 ZonedDateTime - current date/time in default zone
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("1.4 LocalDateTime :- \t" + localDateTime);
// 2. ZonedDateTime, OffsetDateTime, Instant and LocalDateTime in Asia/Dubai Zone
ZoneId zoneId = ZoneId.of("Asia/Dubai");
System.out.println("\n\n2. ZonedDateTime, OffsetDateTime, Instant and LocalDateTime "
+ "in [Asia/Dubai] Zone");
// 2.1 current date/time in specific/passed zone
ZonedDateTime zonedDateTime2 = ZonedDateTime.now(zoneId);
System.out.println("\n2.1 ZonedDateTime :- \t" + zonedDateTime2);
// 2.2 current date/time in specific/passed zone
OffsetDateTime offsetDateTime2 = OffsetDateTime.now(zoneId);
System.out.println("2.2 OffsetDateTime :- \t" + offsetDateTime2);
// 2.3 Instant - current date/time in GMT/UTC
Clock clock = Clock.systemDefaultZone();
Instant instant2 = Instant.now(clock);
System.out.println("2.3 Instant :- \t\t" + instant2);
// 2.4 ZonedDateTime - current date/time in default zone
LocalDateTime localDateTime2 = LocalDateTime.now(zoneId);
System.out.println("2.4 LocalDateTime :- \t" + localDateTime2);
}
}
Output:
1. ZonedDateTime, OffsetDateTime, Instant and LocalDateTime in system default zone - [Asia/Calcutta]
1.1 ZonedDateTime :- 2022-06-29T21:36:19.000938100+05:30[Asia/Calcutta]
1.2 OffsetDateTime :- 2022-06-29T21:36:19.000938100+05:30
1.3 Instant :- 2022-06-29T16:06:19.000938100Z
1.4 LocalDateTime :- 2022-06-29T21:36:19.015938200
2. ZonedDateTime, OffsetDateTime, Instant and LocalDateTime in [Asia/Dubai] Zone
2.1 ZonedDateTime :- 2022-06-29T20:06:19.016938100+04:00[Asia/Dubai]
2.2 OffsetDateTime :- 2022-06-29T20:06:19.016938100+04:00
2.3 Instant :- 2022-06-29T16:06:19.016938100Z
2.4 LocalDateTime :- 2022-06-29T20:06:19.016938100
2. Instant :
- There are 3 ways to get/form an Instant,
- First is to get current date/time or instantaneous moment at GMT/UTC using static factory methods,
A. Instant.now()
B. Instant.now(Clock) - Second is to form an Instant using static factory methods,
A. Instant.ofEpochSecond(long epochSecond)
B. Instant.ofEpochMilli(long epochMilli)
C. Instant.ofEpochSecond(long epochSecond, long nanoAdjustment) - Third and final is to parse date/time at GMT/UTC in String-form to Instant using static factory method parse() such as
2022-06-29T12:01:25.369081700Z
- First is to get current date/time or instantaneous moment at GMT/UTC using static factory methods,
- The fully qualified package/class name of Instant is java.time.Instant i.e.; Instant is present under java.time package
- Class declaration for Instant is as follows,
package java.time;
public final class Instant
implements Temporal, TemporalAdjuster, Comparable<Instant>, Serializable {
}
3. Instant methods or APIs :
Important Instant method details,
- now() – get current date-time to nano-second precision from the GMT/UTC (instantaneous moment at UTC)
- now(Clock) – get current date-time to nano-second precision from the GMT/UTC (instantaneous moment at UTC), Instant are time-zone unaware
- ofEpochSecond(long epochSecond) – get Instant using seconds from the epoch of 1970-01-01T00:00:00Z
- ofEpochMilli(long epochMilli) – get Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z
- ofEpochSecond(long epochSecond, long nanoAdjustment) – get Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second
- parse() – get an instance of Instant from a text string in either yyyy-MM-ddTHH:mm:ss.nnnZ or yyyy-MM-ddTHH:mm:ssZ formats
- atOffset(ZoneOffset offset) – combines invoking Instant with an offset to create an OffsetDateTime
- atZone(ZoneId zone) – combines invoking Instant with a time-zone to create a ZonedDateTime
- getEpochSecond() – get number of seconds from the Java epoch of 1970-01-01T00:00:00Z
- toEpochMilli() – converts Instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z
- getNano() – get number of nanoseconds, later along the time-line, from the start of the second
- plusSeconds(long secondsToAdd) – Returns a copy of this Instant with the specified duration in seconds added
- plusMillis(long millisToAdd) – Returns a copy of this Instant with the specified duration in milliseconds added
- plusNanos(long nanosToAdd) – Returns a copy of this Instant with the specified duration in nanoseconds added
- minusSeconds(long secondsToSubtract) – Returns a copy of this Instant with the specified duration in seconds subtracted
- minusMillis(long millisToSubtract) – Returns a copy of this Instant with the specified duration in milliseconds subtracted
- minusNanos(long nanosToSubtract) – Returns a copy of this Instant with the specified duration in nanoseconds subtracted
- isAfter(Instant otherInstant) – checks if this Instant is after the specified Instant
- isBefore(Instant otherInstant) – checks if this Instant is before the specified Instant
4. Instant examples :
- Get current Instant (date/time) in UTC/GMT
- Instant.now() – get current date/time or instantaneous moment in UTC/GMT
- Instant.now(Clock) – get current date/time or instantaneous moment in UTC/GMT, Instant are time-zone unaware
- Form an instance of Instant from the seconds or milliseconds passed
- Instant.ofEpochSecond(long) – Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z
- Instant.ofEpochMilli(long) – Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z
- Instant.ofEpochSecond(long, long) – Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second
- Instant.parse() – parse Instant from a text string such as 2007-12-03T10:15:30.00Z
- Convert Instant to ZonedDateTime or OffsetDateTime
- atOffset(ZoneOffset) – combines invoking Instant with an offset to create an OffsetDateTime
- atZone(ZoneId) – combines invoking Instant with a time-zone to create a ZonedDateTime
- Get Instant in seconds or milliseconds or nanoseconds
- getEpochSecond() – get invoking Instant into number of seconds from the Java epoch of 1970-01-01T00:00:00Z
- toEpochMilli() – convert invoking Instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z
- getNano() – get invoking Instant into number of nanoseconds, later along the time-line, from the start of the second
- Adding nanoseconds, milliseconds and seconds to Instant using plusNanos(), plusMillis() and plusSeconds() methods respectively
- Subtracting nanoseconds, milliseconds and seconds to Instant using minusNanos(), minusMillis() and minusSeconds() methods respectively
- Check before and after Instant using below methods,
- isBefore(Instant) – checks if invoking Instant is before the specified Instant
- isAfter(Instant) – Checks if invoking Instant is after the specified Instant
4.1 Instant.now() method – get current Instant (date/time) in UTC/GMT:
- Instant.now() captures a moment at UTC/GMT
- Instant.now(Clock) captures a moment at UTC/GMT as Instant are time-zone unaware
- Both overloaded static factory methods now() returns Instant in yyyy-MM-ddTHH:mm:ss.nnnZ format for example 2022-06-29T13:02:58.323249200Z irrespective of time-zone passed
- Read below articles for more details,
InstantExampleUsingNowMethod.java
package in.bench.resources.instant;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
public class InstantExampleUsingNowMethod {
public static void main(String[] args) {
// 1. get an instantaneous moment at GMT/UTC
Instant instant = Instant.now();
System.out.println("1. Current date/time at UTC/GMT is = " + instant);
// 2. get an instantaneous moment at GMT/UTC passing Clock
Clock clock = Clock.system(ZoneId.of("Asia/Dubai"));
Instant instant2 = Instant.now(clock);
System.out.println("\n2. Current date/time at UTC/GMT is = " + instant2);
}
}
Output:
1. Current date/time at UTC/GMT is = 2022-06-29T16:06:42.076995800Z
2. Current date/time at UTC/GMT is = 2022-06-29T16:06:42.111670800Z
4.2 Get an Instant from the seconds or milliseconds:
- Instant.ofEpochSecond(long) – Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z
- Instant.ofEpochMilli(long) – Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z
- Instant.ofEpochSecond(long, long) – Obtains an instance of Instant using seconds from the epoch of 1970-01-01T00:00:00Z and nanosecond fraction of second
- Read Java 8 – How to get Seconds and Nanoseconds from an Instant ? for more details and examples
GetInstantFromSecondAndMilliAndNano.java
package in.bench.resources.instant;
import java.time.Instant;
public class GetInstantFromSecondAndMilliAndNano {
public static void main(String[] args) {
// 1. get an Instant from Milliseconds
Instant instant1 = Instant.ofEpochMilli(Long.valueOf("1656513078830"));
System.out.println("1. Instant.ofEpochMilli(Long.valueOf(\"1656513078830\")) :- "
+ instant1);
// 2. get an Instant from Seconds
Instant instant2 = Instant.ofEpochSecond(1656513061);
System.out.println("\n2. Instant.ofEpochSecond(1656513061) :- "
+ instant2);
// 3. get an Instant from Seconds and Nanoseconds
Instant instant3 = Instant.ofEpochSecond(1656513061, 125);
System.out.println("\n3. Instant.ofEpochSecond(1656513061, 125) :- "
+ instant3);
}
}
Output:
1. Instant.ofEpochMilli(Long.valueOf("1656513078830")) :- 2022-06-29T14:31:18.830Z
2. Instant.ofEpochSecond(1656513061) :- 2022-06-29T14:31:01Z
3. Instant.ofEpochSecond(1656513061, 125) :- 2022-06-29T14:31:01.000000125Z
4.3 Instant.parse() method – get Date/time in String-form:
- Sometimes, we need to parse date/time passed in String-form to an Instant, for that we can use Instant.parse() method which will return Instant in yyyy-MM-ddTHH:mm:ss.nnnZ format
- While parsing Date/Time, value in String-form should be in either of the below formats only, otherwise java.time.format.DateTimeParseException will be thrown
- yyyy-MM-ddTHH:mm:ss.nnnZ
- yyyy-MM-ddTHH:mm:ssZ
- Read Java 8 – How to parse Instant in String form ? for more details and examples
InstantExampleUsingParseMethod.java
package in.bench.resources.instant;
import java.time.Instant;
public class InstantExampleUsingParseMethod {
public static void main(String[] args) {
// 1. parse Instant value in String-form to an Instant
Instant instant1 = Instant.parse("2022-06-29T12:33:45.191546200Z");
System.out.println("1. Parsed Date/time (yyyy-MM-ddTHH:mm:ss.nnnZ) :- "
+ instant1);
// 2. parse Instant value in String-form to an Instant
Instant instant2 = Instant.parse("2022-06-29T12:33:45Z");
System.out.println("\n2. Parsed Date/time (yyyy-MM-ddTHH:mm:ssZ) :- "
+ instant2);
}
}
Output:
1. Parsed Date/time (yyyy-MM-ddTHH:mm:ss.nnnZ) :- 2022-06-29T12:33:45.191546200Z
2. Parsed Date/time (yyyy-MM-ddTHH:mm:ssZ) :- 2022-06-29T12:33:45Z
4.4 Convert Instant to ZonedDateTime or OffsetDateTime:
- atOffset(ZoneOffset) – combines invoking Instant with an offset to create an OffsetDateTime
- Read Java 8 – How to convert Instant to an OffsetDateTime ? for more details and examples
- atZone(ZoneId) – combines invoking Instant with a time-zone to create a ZonedDateTime
- Read Java 8 – How to convert Instant to ZonedDateTime ? for more details and examples
- Read below articles for other conversions like,
- Java 8 – How to convert Instant to LocalDate ?
- Java 8 – How to convert Instant to LocalTime ?
- Java 8 – How to convert Instant to LocalDateTime ?
- Java 8 – How to convert Instant to java.util.Date and vice-versa ?
- Java 8 – How to convert Instant to java.sql.Timestamp and vice-versa ?
- Java 8 – How to convert Instant to Calendar and vice-versa ?
- Java 8 – How to convert Instant to GregorianCalendar and vice-versa ?
- Java 8 – How to convert Instant to XMLGregorianCalendar and vice-versa ?
- Java 8 – How to convert java.util.Date to an Instant in different ways ?
ConvertInstantToZonedAndOffsetDateTime.java
package in.bench.resources.instant;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class ConvertInstantToZonedAndOffsetDateTime {
public static void main(String[] args) {
// 1. get current Instant at UTC
Instant instant = Instant.now();
System.out.println("1. Current Date/time at UTC is :- \n"
+ instant);
// 2. convert Instant into OffsetDateTime
ZoneOffset zoneOffset = ZoneOffset.of("-06:00");
OffsetDateTime offsetDateTime = instant.atOffset(zoneOffset);
System.out.println("\n2. Current Date/time at Offset \"-06:00\" is :- \n"
+ offsetDateTime);
// 3. convert Instant into ZonedDateTime
ZoneId zoneId = ZoneId.of("Australia/Sydney");
ZonedDateTime zonedDateTime = instant.atZone(zoneId);
System.out.println("\n3. Current Date/time at [Australia/Sydney] zone is :- \n"
+ zonedDateTime);
}
}
Output:
1. Current Date/time at UTC is :-
2022-06-29T16:08:22.958632300Z
2. Current Date/time at Offset "-06:00" is :-
2022-06-29T10:08:22.958632300-06:00
3. Current Date/time at [Australia/Sydney] zone is :-
2022-06-30T02:08:22.958632300+10:00[Australia/Sydney]
4.5 Get Instant in seconds or milliseconds or nanoseconds:
- getEpochSecond() – get invoking Instant into number of seconds from the Java epoch of 1970-01-01T00:00:00Z
- toEpochMilli() – convert invoking Instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z
- getNano() – get invoking Instant into number of nanoseconds, later along the time-line, from the start of the second
- Read below articles for more details,
GetInstantInSecondAndMilliAndNano.java
package in.bench.resources.instant;
import java.time.Instant;
public class GetInstantInSecondAndMilliAndNano {
public static void main(String[] args) {
// get current Date/time or Instant at UTC
Instant instant = Instant.now();
// 1. get Nanoseconds from an Instant
int nanos = instant.getNano();
System.out.println("1. Instant in Nanoseconds :- "
+ nanos);
// 2. get Milliseconds from an Instant
long millis = instant.toEpochMilli();
System.out.println("\n2. Instant in Milliseconds :- "
+ millis);
// 2. get Seconds from an Instant
long seconds = instant.getEpochSecond();
System.out.println("\n3. Instant in Seconds :- "
+ seconds);
}
}
Output:
1. Instant in Nanoseconds :- 815586800
2. Instant in Milliseconds :- 1656518931815
3. Instant in Seconds :- 1656518931
4.6 Adding Nano/Millisecond/Second to an Instant:
- Add 125 Nanoseconds to an Instant using plusNanos() method
- Add 999 Milliseconds to an Instant using plusMillis() method
- Add 19 Seconds to an Instant using plusSeconds() method
- Read Java 8 – How to add Second, Millisecond and Nanosecond to an Instant ? for more details and examples
AddToInstant.java
package in.bench.resources.instant;
import java.time.Instant;
public class AddToInstant {
public static void main(String[] args) {
// get current Date/time or Instant at UTC
Instant instant = Instant.now();
System.out.println("Current Instant at UTC is :- "
+ instant);
// 1. add 125 Nanoseconds with current Instant
Instant instant1 = instant.plusNanos(125);
System.out.println("\n1. After adding 125 nanos to an Instant is = "
+ instant1);
// 2. add 999 Milliseconds with current Instant
Instant instant2 = instant.plusMillis(999);
System.out.println("2. After adding 999 millis to an Instant is = "
+ instant2);
// 3. add 19 Seconds with current Instant
Instant instant3 = instant.plusSeconds(19);
System.out.print("3. After adding 19 seconds to an Instant is = "
+ instant3);
}
}
Output:
Current Instant at UTC is :- 2022-08-23T08:06:07.739563Z
1. After adding 125 nanos to an Instant is = 2022-08-23T08:06:07.739563125Z
2. After adding 999 millis to an Instant is = 2022-08-23T08:06:08.738563Z
3. After adding 19 seconds to an Instant is = 2022-08-23T08:06:26.739563Z
4.7 Subtracting Nano/Millisecond/Second to an Instant:
- Subtract 125 Nanoseconds from an Instant using minusNanos() method
- Subtract 999 Milliseconds from an Instant using minusMillis() method
- Subtract 19 Seconds from an Instant using minusSeconds() method
- Read Java 8 – How to subtract Second, Millisecond and Nanosecond from an Instant ? for more details and examples
SubtractFromInstant.java
package in.bench.resources.instant;
import java.time.Instant;
public class SubtractFromInstant {
public static void main(String[] args) {
// get current Date/time or Instant at UTC
Instant instant = Instant.now();
System.out.println("Current Instant at UTC is :- "
+ instant);
// 1. subtract 125 Nanoseconds with current Instant
Instant instant1 = instant.minusNanos(125);
System.out.println("\n1. After subtracting 125 nanos to an Instant is = "
+ instant1);
// 2. subtract 999 Milliseconds with current Instant
Instant instant2 = instant.minusMillis(999);
System.out.println("2. After subtracting 999 millis to an Instant is = "
+ instant2);
// 3. subtract 19 Seconds with current Instant
Instant instant3 = instant.minusSeconds(19);
System.out.print("3. After subtracting 19 seconds to an Instant is = "
+ instant3);
}
}
Output:
Current Instant at UTC is :- 2022-08-23T08:07:36.853582Z
1. After subtracting 125 nanos to an Instant is = 2022-08-23T08:07:36.853581875Z
2. After subtracting 999 millis to an Instant is = 2022-08-23T08:07:35.854582Z
3. After subtracting 19 seconds to an Instant is = 2022-08-23T08:07:17.853582Z
4.8 Check Before/After Instant :
- isBefore(Instant) – checks if invoking Instant is before the specified Instant
- Read Java 8 – How to check whether an Instant is Before another Instant ? for more details and examples
- isAfter(Instant) – Checks if invoking Instant is after the specified Instant
- Read Java 8 – How to check whether an Instant is After another Instant ? for more details and examples
- Read Java 8 – How to compare two Instant instances ? for comparing two instances of Instant
Compare2Instant.java
package in.bench.resources.instant;
import java.time.Instant;
public class Compare2Instant {
public static void main(String[] args) {
// 1. get current Instant at UTC
Instant todayInstant = Instant.now();
System.out.println("1. Current Instant is :- " + todayInstant);
// 2. parse tomorrow Instant
String tomorrowInstantInStr = "2022-06-30T15:10:23.933345200Z";
Instant tomorrowInstant = Instant.parse(tomorrowInstantInStr);
System.out.println("2. Parsed FUTURE Instant is :- " + tomorrowInstant);
// 3. parse yesterday Instant
String yesterdayInstantInStr = "2022-06-28T15:10:23.933345200Z";
Instant yesterdayInstant = Instant.parse(yesterdayInstantInStr);
System.out.println("3. Parsed PAST Instant is :- " + yesterdayInstant);
// 4. isBefore() - Instant comparison
System.out.println("\n4. Instant comparison with isBefore() method :- \n");
// 4.1 check whether current Instant isBefore another tomorrow Instant
boolean isBefore = todayInstant.isBefore(tomorrowInstant);
System.out.println("4.1 Whether current Instant (" + todayInstant
+ ") is Before \n\t another TOMORROW Instant (" + tomorrowInstant + ") :- "
+ isBefore);
// 4.2 check whether current Instant isBefore another yesterday Instant
boolean isBefore2 = todayInstant.isBefore(yesterdayInstant);
System.out.println("4.2 Whether current Instant (" + todayInstant
+ ") is Before \n\t another YESTERDAY Instant (" + yesterdayInstant + ") :- "
+ isBefore2);
// 5. isAfter() - Instant comparison
System.out.println("\n5. Instant comparison with isAfter() methods :- \n");
// 5.1 check whether current Instant isAfter another yesterday Instant
boolean isAfter = todayInstant.isAfter(yesterdayInstant);
System.out.println("5.1 Whether current Instant (" + todayInstant
+ ") is After \n\t another YESTERDAY Instant (" + yesterdayInstant + ") :- "
+ isAfter);
// 5.2 check whether current Instant isAfter another tomorrow Instant
boolean isAfter2 = todayInstant.isAfter(tomorrowInstant);
System.out.println("5.2 Whether current Instant (" + todayInstant
+ ") is After \n\t another TOMORROW Instant (" + tomorrowInstant + ") :- "
+ isAfter2);
}
}
Output:
1. Current Instant is :- 2022-06-29T16:15:30.088237400Z
2. Parsed FUTURE Instant is :- 2022-06-30T15:10:23.933345200Z
3. Parsed PAST Instant is :- 2022-06-28T15:10:23.933345200Z
4. Instant comparison with isBefore() method :-
4.1 Whether current Instant (2022-06-29T16:15:30.088237400Z) is Before
another TOMORROW Instant (2022-06-30T15:10:23.933345200Z) :- true
4.2 Whether current Instant (2022-06-29T16:15:30.088237400Z) is Before
another YESTERDAY Instant (2022-06-28T15:10:23.933345200Z) :- false
5. Instant comparison with isAfter() methods :-
5.1 Whether current Instant (2022-06-29T16:15:30.088237400Z) is After
another YESTERDAY Instant (2022-06-28T15:10:23.933345200Z) :- true
5.2 Whether current Instant (2022-06-29T16:15:30.088237400Z) is After
another TOMORROW Instant (2022-06-30T15:10:23.933345200Z) :- false
Q) How to get Zones with Offset Z or +00:00 or UTC/GMT ?
- ZoneId.getAvailableZoneIds(); provides all Zones in the form of Set<String>
- To get Zones under specific Offset like “Z” or +00:00 or UTC/GMT, we can get stream and process as shown in the below illustration
- Read Java 8 – How to display Zones for particular Offset ? for more details and examples
DisplayAllZonesForOffsetZ.java
package in.bench.resources.instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Set;
public class DisplayAllZonesForOffsetZ {
public static void main(String[] args) {
// 1. get all zones
Set<String> zones = ZoneId.getAvailableZoneIds();
// 1.1 print to console
System.out.println("Zones with Offset Z or +00:00 or UTC/GMT :- \n");
// 2. extract zones with Offset Z (+00:00) and print to console
zones // original source
.stream() // get stream
.map(zone -> ZonedDateTime.now(ZoneId.of(zone))) // convert to ZonedDateTime
.filter(zdt -> zdt.getOffset().toString().equalsIgnoreCase("Z")) // Filter Offset with Z
.sorted((zdt1, zdt2) -> zdt1.getZone().toString().compareTo(zdt2.getZone().toString())) // sorting
.forEach(zdt -> System.out.println(zdt.getOffset() + "\t" + zdt.getZone())); // printing
}
}
Output:
Zones with Offset Z or +00:00 or UTC/GMT :-
Z Africa/Abidjan
Z Africa/Accra
Z Africa/Bamako
Z Africa/Banjul
Z Africa/Bissau
Z Africa/Conakry
Z Africa/Dakar
Z Africa/Freetown
Z Africa/Lome
Z Africa/Monrovia
Z Africa/Nouakchott
Z Africa/Ouagadougou
Z Africa/Sao_Tome
Z Africa/Timbuktu
Z America/Danmarkshavn
Z America/Scoresbysund
Z Atlantic/Azores
Z Atlantic/Reykjavik
Z Atlantic/St_Helena
Z Etc/GMT
Z Etc/GMT+0
Z Etc/GMT-0
Z Etc/GMT0
Z Etc/Greenwich
Z Etc/UCT
Z Etc/UTC
Z Etc/Universal
Z Etc/Zulu
Z GMT
Z GMT0
Z Greenwich
Z Iceland
Z UCT
Z UTC
Z Universal
Z Zulu
Related Articles:
- Java 8 – LocalDate with method details and examples
- Java 8 – LocalTime with method details and examples
- Java 8 – LocalDateTime with method details and examples
- Java 8 – ZonedDateTime with method details and examples
- Java 8 – Display all Zones and its Offset using ZoneId and ZoneOffset
- Java 8 – OffsetDateTime with method details and examples
- Java 8 – Instant with method details and examples
- Java 8 – How to sort List by java.util.Date in different ways
- Java 8 – How to sort List by java.time.LocalDate in different ways
- Java 8 – How to sort List by java.time.LocalDateTime in different ways
References:
- https://docs.oracle.com/javase/7/docs/api/java/util/Date.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
- https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html
- https://docs.oracle.com/javase/7/docs/api/java/sql/Time.html
- https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
- https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
- https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html
- https://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html
- https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
Happy Coding !!
Happy Learning !!