java - 无论日期如何,检查给定时间是否介于两次之间

标签 java android date calendar timespan

我有时间跨度:

String time1 = 01:00:00

String time2 = 05:00:00

我想检查 time1time2 是否都在 20:11:13 and 14:49:00 之间.

其实,01:00:00大于 20:11:13小于 14:49:00考虑 20:11:13总是小于 14:49:00 .这是先决条件。

所以我想要的是,20:11:13 < 01:00:00 < 14:49:00 .

所以我需要这样的东西:

 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;
    }
 }

我知道这段代码在比较字符串对象时没有给出正确的结果。

如何做到这一点,因为它们是时间跨度而不是要比较的字符串?

最佳答案

您可以使用 Calendar 类进行检查。

例如:

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();
}

关于java - 无论日期如何,检查给定时间是否介于两次之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17697908/

相关文章:

java - 不支持的类文件主要版本 61 Cordova Mac

android - 在 flutter 中导入下拉依赖项 : ^ 1. 0.2 时出现问题

java - 在 Spring REST Controller 中读取 HTTP header

Java 如何使用 Maven 子项目进行集成测试?

android - 无法接收 gcm 消息

两个 Date() 之间的 JavaScript 差异(以月为单位)

Windows 批处理文件将输出重定向到带有日期/时间的日志文件

php - mysql utcdate 字符串比较 codeigniter

Java TCP Echo 服务器 - 广播

java - 使用jmeter执行简单的java文件