gpt4 book ai didi

Java:计算持续时间

转载 作者:行者123 更新时间:2023-11-29 06:48:10 26 4
gpt4 key购买 nike

我创建了以下代码来计算可以有两种不同格式的两个时间戳之间的持续时间:

public class dummyTime {
public static void main(String[] args) {
try {
convertDuration("2008-01-01 01:00 pm - 01:56 pm");
convertDuration("2008-01-01 8:30 pm - 2008-01-02 09:30 am");
} catch (Exception e) {
e.printStackTrace();
}
}

private static String convertDuration(String time) throws Exception {
String ts[] = time.split(" - ");
SimpleDateFormat formatNew = new SimpleDateFormat("HH:mm");
Date beg, end;
String duration = null;

beg = getDateTime(ts[0]);
end = getDateTime(ts[1], beg);

duration = formatNew.format(end.getTime() - beg.getTime());
System.out.println(duration + " /// " + time + " /// " + beg + " /// "
+ end);

return duration;
}

private static Date getDateTime(String dateTime) throws ParseException {
DateFormat formatOldDateTime = new SimpleDateFormat(
"yyyy-MM-dd hh:mm aa");
DateFormat formatOldTimeOnly = new SimpleDateFormat("hh:mm aa");
Date date = null;

try {
date = formatOldDateTime.parse(dateTime);
} catch (ParseException e) {
date = formatOldTimeOnly.parse(dateTime);
}

return date;
}

private static Date getDateTime(String dateTime, Date orig)
throws ParseException {
Date end = getDateTime(dateTime);

if (end.getYear() == 70) {
end.setYear(orig.getYear());
end.setMonth(orig.getMonth());
end.setDate(orig.getDate());
}

return end;
}
}

它生成的输出是:

01:56 /// 2008-01-01 01:00 pm - 01:56 pm /// Tue Jan 01 13:00:00 CET 2008 /// Tue Jan 01 13:56:00 CET 2008
14:00 /// 2008-01-01 8:30 pm - 2008-01-02 09:30 am /// Tue Jan 01 20:30:00 CET 2008 /// Wed Jan 02 09:30:00 CET 2008

我的问题是:

  1. 为什么结果总是错误的(总是+1h)?
  2. 什么是更好的识别时间戳的方法天? == 70 看起来不太好而且getDay 和 setDay 函数是也已弃用。

非常感谢,这个问题让我抓狂了几个小时。

最佳答案

您正在格式化一天中的时间,而不是小时数和分钟数。由于您在冬季处于 CET 时区 [中欧时间],因此与 UTC(“GMT”)相差一小时。

您可能希望使用 Calendar 而不是 Date。或者 Joda-Time .

关于Java:计算持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/477842/

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