【问题标题】:Difference in time - from before midnight to after midnight without date时差 - 从午夜之前到午夜之后没有日期
【发布时间】:2018-04-12 08:24:56
【问题描述】:

午夜过后,我正在努力计算时间:

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

【问题讨论】:

  • 您可以添加一个检查来验证日期 2 是否在日期 1 之前。在这种情况下,您可以使用 24h-(date1-date2) 来找出两者之间的实际差异日期 1 和日期 2
  • 夏令时怎么样? 22:00-04:00 可能相差 5、6 或 7 个小时,具体取决于一年中的哪一天。
  • 问题是什么?
  • Date 类早已过时,尤其是SimpleDateFormat 也是出了名的麻烦。您可能想忘记这些类,而使用java.time, the modern Java date and time API。使用起来感觉好多了。

标签: java time


【解决方案1】:

如果您不关心夏令时的变化并且您认为世界是理想的(事实并非如此),您可以减去结束和开始之间的持续时间(将 end 视为开始和 start作为结束)从 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)));
}

【讨论】:

    猜你喜欢
    • 2016-01-13
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    相关资源
    最近更新 更多