如何在java中找到两个日期之间差异的持续时间? [英] How to find the duration of difference between two dates in java?

查看:22
本文介绍了如何在java中找到两个日期之间差异的持续时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个DateTime对象,需要找出它们的持续时间

I have two objects of DateTime, which need to find the duration of their difference,

我有以下代码,但不确定如何继续以达到以下预期结果:

I have the following code but not sure how to continue it to get to the expected results as following:

示例:

      11/03/14 09:30:58
      11/03/14 09:33:43
      elapsed time is 02 minutes and 45 seconds
      -----------------------------------------------------
      11/03/14 09:30:58 
      11/03/15 09:30:58
      elapsed time is a day
      -----------------------------------------------------
      11/03/14 09:30:58 
      11/03/16 09:30:58
      elapsed time is two days
      -----------------------------------------------------
      11/03/14 09:30:58 
      11/03/16 09:35:58
      elapsed time is two days and 05 minutes
      

代码:

    String dateStart = "11/03/14 09:29:58";
    String dateStop = "11/03/14 09:33:43";

    Custom date format
    SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");

    Date d1 = null;
    Date d2 = null;
    try {
        d1 = format.parse(dateStart);
        d2 = format.parse(dateStop);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // Get msec from each, and subtract.
    long diff = d2.getTime() - d1.getTime();
    long diffSeconds = diff / 1000 % 60;
    long diffMinutes = diff / (60 * 1000) % 60;
    long diffHours = diff / (60 * 60 * 1000);
    System.out.println("Time in seconds: " + diffSeconds + " seconds.");
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");
    System.out.println("Time in hours: " + diffHours + " hours.");

推荐答案

试试下面的

{
        Date dt2 = new DateAndTime().getCurrentDateTime();

        long diff = dt2.getTime() - dt1.getTime();
        long diffSeconds = diff / 1000 % 60;
        long diffMinutes = diff / (60 * 1000) % 60;
        long diffHours = diff / (60 * 60 * 1000);
        int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24));

        if (diffInDays > 1) {
            System.err.println("Difference in number of days (2) : " + diffInDays);
            return false;
        } else if (diffHours > 24) {

            System.err.println(">24");
            return false;
        } else if ((diffHours == 24) && (diffMinutes >= 1)) {
            System.err.println("minutes");
            return false;
        }
        return true;
}

这篇关于如何在java中找到两个日期之间差异的持续时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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