如何在Android中获取两个时间的分钟差 [英] how to get minutes difference between two time in android

查看:0
本文介绍了如何在Android中获取两个时间的分钟差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public int difftime(String string, String string2) {
        int hours;
        int min = 0;
        int days;
        long difference ;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            Date date1 = simpleDateFormat.parse("08:00 AM");
            Date date2 = simpleDateFormat.parse("04:00 PM");

             difference = date2.getTime() - date1.getTime();
             days = (int) (difference / (1000 * 60 * 60 * 24));
            hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
             min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))
                    / (1000 * 60);
            hours = (hours < 0 ? -hours : hours);
            Log.i("======= Hours", " :: " + hours);
            return min;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return min;
    }

这是我的函数,以分钟为单位获取时间差,但它始终为零。我不知道我哪里搞错了,请告诉我哪里搞错了。我希望会议记录形式的结果。

推荐答案

首先,您犯了非常基本的错误。对于12小时制,您应该使用HH而不是HH。令我惊讶的是,没有一个答案能纠正这个错误。

其次,您考虑的不是日期,而是时间。所以上午8:00和下午4:00没有任何分钟差异。只有8小时的差异。

因此,现在在您的情况下,您必须根据两种情况计算分钟,一种是从小时计算,另一种是当存在分钟差时计算分钟。我改正你的代码。请检查一下,因为这在我这一端工作正常。

public long diffTime() {
    long min = 0;
    long difference ;
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm aa"); // for 12-hour system, hh should be used instead of HH
        // There is no minute different between the two, only 8 hours difference. We are not considering Date, So minute will always remain 0
        Date date1 = simpleDateFormat.parse("08:00 AM");
        Date date2 = simpleDateFormat.parse("04:00 PM");

        difference = (date2.getTime() - date1.getTime()) / 1000;
        long hours = difference % (24 * 3600) / 3600; // Calculating Hours
        long minute = difference % 3600 / 60; // Calculating minutes if there is any minutes difference
        min = minute + (hours * 60); // This will be our final minutes. Multiplying by 60 as 1 hour contains 60 mins
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return min;
}

这篇关于如何在Android中获取两个时间的分钟差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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