[英]How to Compare a Time with two other time provided?
令人困惑..就像我們在比較時間一樣,絕對不建議使用字符串...但是,如果格式為(HH:mm:ss)。 我應該如何比較他們做某事?
例如:Target1:9:00:00 Target2:23:00:00
輸入大於Target1小於Target2時,如何做比較邏輯?
if(input > Target1 && input < Target2){
//do statement A
}else{
//do statement B
}
所以,如果我的輸入時間是10:00:00,它應該運行語句A,如果輸入時間是23:01:00,它應該運行語句B我應該怎么做? 在時間格式上大於(>)小於(<)?
給定它們作為字符串,您可以將它們從SimpleDateFormat轉換為Date對象。
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
最簡單的方法是通過執行以下操作將它們轉換為毫秒數
long time1 = sdf.parse(Target1).getTime();
long time2 = sdf.parse(Target2).getTime();
long inputTime = sdf.parse(input).getTime();
這樣,您實際上是在進行整數比較,因此您可以忽略所有“日期時間”業務。
if(inputTime > time1 && inputTime < time2)
SimpleDateFormat df=new SimpleDateFormat("hh:mm:ss");
Date d1=df.parse(dateToPars);
d1.after(otherTimeYouWantTocompare); OR
d1.before(otherTimeYouWantTocompare);
但是您必須以上述格式提供時間
您可以使用日歷功能.getTimeInMillis()計算時差,並獲得2個時差,這里您只需要在日歷中設置特定時間並進行比較即可
try{
Calendar calender = Calendar.getInstance();
Calendar calDb = Calendar.getInstance();
Calendar matchd = Calendar.getInstance();
mYear = calender.get(Calendar.YEAR);
mMonth = calender.get(Calendar.MONTH);
mDay = calender.get(Calendar.DAY_OF_MONTH);
mendYear = calDb.get(Calendar.YEAR);
mendMonth = calDb.get(Calendar.MONTH);
mendDay = calDb.get(Calendar.DAY_OF_MONTH);
// Here you can change day values
calDb.set(Calendar.DAY_OF_MONTH, mDay-1);
strbeforedate = mDateFormat.format(calDb.getTime());
curentdate = mDateFormat.format(calender.getTime());
calDb.setTime(mDateFormat.parse(strbeforedate));
calender.setTime(mDateFormat.parse(curentdate));
String mydate = "2013.03.14 03:11";
String mdatetime = "";
deletepath = new ArrayList<String>();
try{
// here your matching goes and pass date here
matchd.setTime(mDateFormat.parse(mdatetime));
long diff = calDb.getTimeInMillis() - calender.getTimeInMillis();
long matchdiff = matchd.getTimeInMillis() - calender.getTimeInMillis();
if(diff < matchdiff){
// do your work here
}else{
// do your else work here
}
}catch(Exception e){
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.