0

I'm converting UTC format to local time and I want to check if input date dateObj.lastModified() is greater than this date Sat Jan 29 11:44:43 EST 2022 or not. Please find my code below:

I'm able to convert UTC date to local date time but I'm struggling how to check in if condition.

dateObj.lastModified() value:

2022-01-29T16:44:28Z
2022-01-30T04:54:31Z
2022-01-30T04:54:32Z
2022-01-29T16:44:42
2022-01-29T16:44:43Z
2022-01-29T16:44:43Z

MyDate.java

    LocalDateTime ldt = LocalDateTime.ofInstant(dateObj.lastModified(),
            ZoneId.systemDefault());
    ZonedDateTime zdt = ldt.atZone(ZoneId.systemDefault());
    Date output = Date.from(zdt.toInstant());
    System.out.println("Date output: " +output);
    Instant instant1
            = Instant.parse("Sat Jan 29 11:44:43 EST 2022");

    if (output.after(Date.from(instant1))) {
        System.out.println("true");
    }

My UTC date got converted properly in this line Date output = Date.from(zdt.toInstant());

But code is failing in if condition, can you please help how to check dateObj.lastModified is greater than this date Sat Jan 29 11:44:43 EST 2022 or not

Appreciated your help. Thanks~

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Brady Maf
  • 1,279
  • 2
  • 5
  • 12
  • 2
    Just compare two ZonedDateTime, it's the Java 8 way. – Guillaume F. Jan 30 '22 at 23:37
  • `LocalDateTime.ofInstant(dateObj.lastModified()` suggests that `dateObj.lastModified()` is already an `Instant` – MadProgrammer Jan 30 '22 at 23:45
  • 2
    The terrible `java.util.Date` class was replaced by `java.time.Instant`. Avoid using the legacy date-time classes such as `Date` & `Calendar`. Use only *java.time*. – Basil Bourque Jan 30 '22 at 23:58
  • 2
    You seem to be going through unnecessary gyrations with `LocalDateTime` and `Date`. If you want to compare two moments, just use `isAfter`/`isBefore` with a pair of `Instant` or `ZonedDateTime` objects. Don't overthink it. Example: `if( Instant.parse( "2022-01-29T16:44:28Z" ).isBefore( ZonedDateTime.of( 2022 , 1 , 29 , 11 , 44 , 43 , 0 , ZoneId.of( "America/New_York" ) ).toInstant() ) { … }`. Or: `Instant.parse( "2022-01-29T16:44:28Z" ).atZone( ZoneId.of( "America/New_York" ) ).isBefore( otherZonedDateTime )`. – Basil Bourque Jan 30 '22 at 23:59

0 Answers0