gpt4 book ai didi

java - 时间差 - 从午夜之前到午夜之后,无日期

转载 作者:行者123 更新时间:2023-12-01 16:46:22 32 4
gpt4 key购买 nike

午夜过后我很难计算时间:

String time = "15:00-18:05"; //Calculating OK
//String time = "22:00-01:05"; //Not calculating properly
String[] parts = time.split("-");

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
Date date2 = null;
Date dateMid = null;


String dateInString = "24:00";
try {
dateMid = format.parse(dateInString);
} catch (ParseException e1) {
e1.printStackTrace();
}

try {
date1 = format.parse(parts[0]);
date2 = format.parse(parts[1]);
} catch (ParseException e) {
e.printStackTrace();
}

long difference = date2.getTime() - date1.getTime();


if (date2.getTime()<date1.getTime()) //in case beyond midnight calculation
{
difference = dateMid.getTime()-difference;
}



int minutes = (int) ((difference / (1000*60)) % 60);
int hours = (int) ((difference / (1000*60*60)) % 24);

String tot = String.format("%02d:%02d", hours,minutes);
System.out.println("dif2: "+tot);

最佳答案

如果您不关心夏令时的变化,并且您认为世界是理想的(事实并非如此),您只需减去结束和开始之间的持续时间(将 end 视为开始并开始作为结束)从24小时开始:

String time = "22:00-01:05";
String[] parts = time.split("-");

LocalTime start = LocalTime.parse(parts[0]);
LocalTime end = LocalTime.parse(parts[1]);
if (start.isBefore(end)) { // normal case
System.out.println(Duration.between(start, end));
} else { // 24 - duration between end and start, note how end and start switched places
System.out.println(Duration.ofHours(24).minus(Duration.between(end, start)));
}

关于java - 时间差 - 从午夜之前到午夜之后,无日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49791495/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com