java 判断一个string类型时间是否包含另一个时间段HHmm格式
可以使用Java中的SimpleDateFormat类来将字符串转换为Date对象,然后比较时间段是否重叠。
以下是一个示例代码:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeOverlapChecker {
public static void main(String[] args) throws ParseException {
String time1 = "10:00";
String time2 = "12:00";
String time3 = "11:00";
String time4 = "13:00";
boolean overlap1 = checkOverlap(time1, time2, time3);
boolean overlap2 = checkOverlap(time1, time2, time4);
System.out.println("Overlap1: " + overlap1);
System.out.println("Overlap2: " + overlap2);
}
public static boolean checkOverlap(String time1, String time2, String time3) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date start1 = format.parse(time1);
Date end1 = format.parse(time2);
Date start2 = format.parse(time3);
Date end2 = new Date(start2.getTime() + (end1.getTime() - start1.getTime()));
return !(end2.before(start2) || end1.before(start2));
}
}
在此示例中,我们将时间字符串转换为Date对象,并使用Date对象进行比较。我们还使用SimpleDateFormat类来解析和格式化时间字符串。
checkOverlap方法接受3个时间字符串作为参数,并返回一个布尔值,表示时间段是否重叠。我们首先将时间1和时间2转换为Date对象,并计算出时间段1的结束时间。然后,我们将时间3转换为Date对象,并计算出时间段2的结束时间。最后,我们比较两个时间段是否重叠。
在上面的示例中,时间段1为10:00到12:00,时间段2为11:00到13:00。因此,Overlap1应该为true,Overlap2应该为false
原文地址: https://www.cveoy.top/t/topic/hb0k 著作权归作者所有。请勿转载和采集!