如何在Java中比较Date中的时间部分

时间:2018-10-22 13:06:41

标签: java android date

我需要比较2个日期/时间变量中的时间部分,以查看时间是否在android中的当前时间之间。我该怎么办?

    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;
}

1 个答案:

答案 0 :(得分:0)

如果您只需要比较时间,而忽略日期,那么您应该做类似的事情,这样您的“日期”部分在所有三个变量中都相等。

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()));
}