简体   繁体   中英

how to compare date without time using calendar in java?

I want to compare two date type only date not time.

date1 = 2022.10.10 16:30:40 date2 = 2022.10.10 13:30:40

these dates are same date so I want to return true.

below is my code. is there clean code?

public Boolean a0160(HashMap<String, Object> params){
        Date accessRecord;
        Date now = new Date();
        accessRecord = userMapper.a0170(params);
        Calendar calAccessRecord = Calendar.getInstance();
        Calendar calOneHourBefore = Calendar.getInstance();
        calAccessRecord.setTime(accessRecord);
        calOneHourBefore.setTime(now);
        calOneHourBefore.add(Calendar.HOUR, -1);

        int calOneHourBeforeYear = calOneHourBefore.get(Calendar.YEAR);
        int calOneHourBeforeMonth = calOneHourBefore.get(Calendar.MONTH);
        int calOneHourBeforeDate = calOneHourBefore.get(Calendar.DATE);

        int calAccessRecordYear = calAccessRecord.get(Calendar.YEAR);
        int calAccessRecordMonth = calAccessRecord.get(Calendar.MONTH);
        int calAccessRecordDate = calAccessRecord.get(Calendar.DATE);

        if(calOneHourBeforeYear == calAccessRecordYear && calAccessRecordMonth == calOneHourBeforeMonth && calAccessRecordDate == calOneHourBeforeDate){
            return true;
        } else {
            return false;
        }
    }

tl;dr

myJavaUtilDate
.toInstant() 
.atZone( 
    ZoneId.of( "Pacific/Auckland" )
)
.toLocalDate()
.isEqual(
    ZonedDateTime
    .now( ZoneId.of( "Pacific/Auckland" ) )
    .minusHours( 1 )
    .toLocalDate()
)

java.time

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

Apparently you are handed a java.util.Date object. The first thing to do is convert from the flawed legacy to its modern replacement, java.time.Instant . Use new conversion methods added to the old classes.

Instant instant = myJavaUtilDate.toInstant() ;

Both the legacy and modern classes represent a moment as seen with an offset from UTC of zero hours-minutes-seconds.

Understand that for any given moment, the date varies around the globe by time zone. So determining a date requires the context of a time zone.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

Extract the date portion.

LocalDate ld = zdt.toLocalDate() ;

Apparently you want to compare that to the current date as of one hour ago.

LocalDate dateAnHourAgo = ZonedDateTime.now( z ).minusHours( 1 ).toLocalDate() ;

Compare with isEqual , isBefore , and isAfter methods.

They aren't dates; they're strings:

return date2.startsWith(date1.substring(0, 10));

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