简体   繁体   中英

Compare java.util.Calendar date to java.util.Date

I need to compare a Calendar time to Date. I wrote below code.

Calendar now = Calendar.getInstance();
now.set(Calendar.SECOND, 0);
Date date = new Date();
date.setSeconds(0);
System.out.println(date);
System.out.println(now.getTime());
System.out.println(date.compareTo(now.getTime()));

Output is

Fri Dec 01 16:54:00 IST 2017
Fri Dec 01 16:54:00 IST 2017
1

It seems util date is bigger than calendar date. Why is it failing? what is the write way of comparing these dates?

Edit 1:- My problem is I need to compare a util date (stored in database) lets say 2017-12-01 16:41:00.0 to current Date and time, what is write approach?

Check the millis:

    System.out.println(now.getTime().getTime());
    System.out.println(date.getTime());
    System.out.println(now.getTime().getTime() - date.getTime());

Then you see that there (sometimes) is a difference.

A simple way to remove the seconds/millis is to count the number of minutes

// compare the minutes, ignoring the seconds/milli-seconds.
if (now.getTime().getTime() / 60_000 == date.getTime() / 60_000)

You can also use TimeUnit

if (TimeUnit.MILLISECONDS.toMinutes(now.getTime().getTime()) == 
    TimeUnit.MILLISECONDS.toMinutes(date.getTime()))

if you prefer to use a library than maths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM