[英]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.我需要比较 2 个日期/时间变量的时间部分,以查看时间是否介于 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()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.