[英]how do I compare time part from Date in java
我需要比較 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;
}
如果您只需要比較時間而忽略日期,那么您應該這樣做,這樣您的“日期”部分在所有三個變量中都相等。
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()));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.