Difference in time - from before midnight to after midnight without date

后端 未结 1 1006
天涯浪人
天涯浪人 2020-12-07 06:01

I am struggling to calculate time when going after midnight:

String time = \"15:00-18:05\"; //Calculating OK
    //String time = \"22:00-01:05\"; //Not calcu         


        
相关标签:
1条回答
  • 2020-12-07 06:53

    If you don't care about daylight saving changes and you assume the world is ideal (which it isn't), you can just subtract the duration between end and start (treating end as the start and start as the end) from 24 hours:

    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)));
    }
    
    0 讨论(0)
提交回复
热议问题