时间差-从午夜之前到午夜之后(无日期) [英] Difference in time - from before midnight to after midnight without date

查看:85
本文介绍了时间差-从午夜之前到午夜之后(无日期)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

如果您不关心夏令时的变化,并且假设世界是理想的(不是理想的),则可以减去两点之间的持续时间然后从24小时开始(将end作为开始,将start作为结束):

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

这篇关于时间差-从午夜之前到午夜之后(无日期)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆