問(wèn)題描述
我有時(shí)間跨度:
字符串時(shí)間1 = 01:00:00
String time1 = 01:00:00
字符串時(shí)間2 = 05:00:00
String time2 = 05:00:00
我想檢查 time1 和 time2 是否都在 20:11:13 和 14:49:00
之間.
I want to check if time1 and time2 both lies between 20:11:13 and 14:49:00
.
實(shí)際上,考慮到,
始終小于 01:00:00
大于20:11:13
且小于14:49:00
>20:11:1314:49:00
.這是先決條件.
Actually, 01:00:00
is greater than 20:11:13
and less than 14:49:00
considering 20:11:13
is always less than 14:49:00
. This is given prerequisite.
所以我想要的是,20:11:13 <01:00:00 <14:49:00
.
所以我需要這樣的東西:
So I need something like that:
public void getTimeSpans()
{
boolean firstTime = false, secondTime = false;
if(time1 > "20:11:13" && time1 < "14:49:00")
{
firstTime = true;
}
if(time2 > "20:11:13" && time2 < "14:49:00")
{
secondTime = true;
}
}
我知道這段代碼在比較字符串對(duì)象時(shí)沒(méi)有給出正確的結(jié)果.
I know that this code does not give correct result as I am comparing the string objects.
如何做到這一點(diǎn),因?yàn)樗鼈兪菚r(shí)間跨度而不是要比較的字符串?
How to do that as they are the timespans but not the strings to compare?
推薦答案
您可以使用 Calendar
類(lèi)進(jìn)行檢查.
You can use the Calendar
class in order to check.
例如:
try {
String string1 = "20:11:13";
Date time1 = new SimpleDateFormat("HH:mm:ss").parse(string1);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(time1);
calendar1.add(Calendar.DATE, 1);
String string2 = "14:49:00";
Date time2 = new SimpleDateFormat("HH:mm:ss").parse(string2);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(time2);
calendar2.add(Calendar.DATE, 1);
String someRandomTime = "01:00:00";
Date d = new SimpleDateFormat("HH:mm:ss").parse(someRandomTime);
Calendar calendar3 = Calendar.getInstance();
calendar3.setTime(d);
calendar3.add(Calendar.DATE, 1);
Date x = calendar3.getTime();
if (x.after(calendar1.getTime()) && x.before(calendar2.getTime())) {
//checkes whether the current time is between 14:49:00 and 20:11:13.
System.out.println(true);
}
} catch (ParseException e) {
e.printStackTrace();
}
這篇關(guān)于無(wú)論日期如何,檢查給定時(shí)間是否介于兩次之間的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!