Check if a given time lies between two times regardless of date(无论日期如何,检查给定时间是否介于两次之间)
问题描述
我有时间跨度:
字符串时间1 = 01:00:00
String time1 = 01:00:00
字符串时间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
.
实际上,考虑到,
始终小于 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;
}
}
我知道这段代码在比较字符串对象时没有给出正确的结果.
I know that this code does not give correct result as I am comparing the string objects.
如何做到这一点,因为它们是时间跨度而不是要比较的字符串?
How to do that as they are the timespans but not the strings to compare?
推荐答案
您可以使用 Calendar
类进行检查.
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();
}
这篇关于无论日期如何,检查给定时间是否介于两次之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无论日期如何,检查给定时间是否介于两次之间
基础教程推荐
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01