Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to compare date object without seconds

Tags:

java

I take two date time object in database. And I need to compare it without seconds.

Date 1 Value : 2018-05-25T13:55:24.000+05:30 Date 2 value : 2018-05-31T08:31:00.000+05:30

I need to check date 1 is after date 2.

if(Checks.checkNotNull(dateTime) && (partiallyInvalidateDate.isAfter(dateTime))){
    code = null;
  }

but I need to do above comparison without second part. Need some expert help to do it.

like image 383
uma Avatar asked Oct 24 '25 14:10

uma


1 Answers

Assuming you're getting date times from java.sql.ResultSet as java.sql.Timestamp, you can set the seconds and nanos directly on those objects then compare with after (though you'll get a deprecated warning on setSeconds). Test with mock Timestamps:

import java.sql.Timestamp;

public class TestTimestamp {

     public static void main(String []args){
        Timestamp ts1 = Timestamp.valueOf("2011-12-25 11:12:13");
        Timestamp ts2 = Timestamp.valueOf("2011-12-25 11:12:14");

        ts1.setSeconds(0);
        ts1.setNanos(0);
        ts2.setSeconds(0);
        ts2.setNanos(0);

        System.out.println(ts1);
        System.out.println(ts2);
        //should print false since they're now identical
        System.out.println(ts2.after(ts1));
    }
}

If you need to use LocalDateTime, do this:

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Test{

     public static void main(String []args){
        Timestamp ts1 = Timestamp.valueOf("2011-12-25 11:12:13");
        Timestamp ts2 = Timestamp.valueOf("2011-12-25 11:12:14");

        LocalDateTime dt1 = ts1.toLocalDateTime().truncatedTo(ChronoUnit.MINUTES);
        LocalDateTime dt2 = ts2.toLocalDateTime().truncatedTo(ChronoUnit.MINUTES);

        System.out.println(dt1);
        System.out.println(dt2);
        //should print false since they're now identical
        System.out.println(dt2.isAfter(dt1));
     }
}
like image 142
ACHC Avatar answered Oct 27 '25 03:10

ACHC