Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two instants in Java?

Tags:

java

I want comparison two Instants to see if equals both or greater than, but i can’t. i dont know. how i can compare instants?

  private Instant expiration;

 if(expiration()==Instant.now()||expiration()>Instant.now())
  {
     valid+="the Expire date is invalid check it . ";
  }

i try this way but i have compile error. but i think cant comparison in this way it must change instant to String and compare after it but i dont know how to format to string

like image 944
Abdalrhman Alkraien Avatar asked Feb 16 '26 07:02

Abdalrhman Alkraien


2 Answers

Don't convert them to Strings. Instant, like every other Comparable type, has the compareTo method. Use it like this:

if (expiration.compareTo(Instant.now()) >= 0) {
  ...
}
like image 189
Louis Wasserman Avatar answered Feb 18 '26 21:02

Louis Wasserman


Posting comments by chrylis-cautiouslyoptimistic as an answer to highlight


Instant also has more semantically meaningful methods isAfter and isBefore

if (now().isAfter(expiration)) {
  .. do something ..
}

As pointed out by @Louis Wasserman **

  • Note that isAfter doesn't represent >=, it represents >
  • You could work around that, e.g. with !isBefore or || equals
like image 27
y2k-shubham Avatar answered Feb 18 '26 20:02

y2k-shubham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!