简体   繁体   中英

how do I compare time part from Date in java

I need to compare the time part from 2 date/time variables to see if the time is inbetween the current time in android. How can I do that?

    Boolean InBetweenTime(Date currentTime, Date StartTime, Date EndTime)
{
    Boolean result = false;
    Calendar calendar = Calendar.getInstance();
    if ((!currentTime.before(StartTime))&&(!currentTime.after(EndTime))){
        //between time
    } else {
        //not inbetween time
    }
    return result;
}

If what you need is to compare only time, ignoring date, then you should do something like this, so your 'date' part be equal in all three variables.

Boolean InBetweenTime(Date currentTime, Date startTime, Date endTime){
    Boolean result = false;

    //calendar for currentTime
    Calendar currentCal = Calendar.getInstance();
    currentCal.setTime(currentTime);
    //calendar for startTime
    Calendar startCal = Calendar.getInstance();
    startCal.setTime(startTime);
    //calendar for endTime
    Calendar endCal = Calendar.getInstance();
    endCal.setTime(endTime);
    //set corresponding date fields of startTime and endTime to be equal t ocurrentTime, so you compare only time fields
    startCal.set(currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH), currentCal.get(Calendar.DAY_OF_MONTH));
    endCal.set(currentCal.get(Calendar.YEAR), currentCal.get(Calendar.MONTH), currentCal.get(Calendar.DAY_OF_MONTH));
    //return true if between, false otherwise
    return (!currentTime.before(startCal.getTime())) && (!currentTime.after(endCal.getTime()));
}

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