找到两个时间值之间的时间差总是给出“秒"值为 0 [英] Find the difference in time between two time values always gives the "Second" value as 0

查看:42
本文介绍了找到两个时间值之间的时间差总是给出“秒"值为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以 HH:MM:SS 格式找出当前时间值和未来时间之间的差异.

I'm trying to find the difference between current time value and a future time in HH:MM:SS format.

例如:
当 date1 为2017-05-11T20:30"且 date2 为2017-05-11T21:40"时,输出应为 01:10:00.

For example:
When date1 is "2017-05-11T20:30" and date2 is "2017-05-11T21:40", the output should be 01:10:00.

这是我正在尝试的代码,其中我试图找到当前时间和未来时间值之间的差异:

Here's the code I'm trying, wherein I'm trying to find the difference between current time and a future time value:

public void updateTimeRemaining() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
    String currentTime = simpleDateFormat.format(new Date());
    long difference = simpleDateFormat.parse(endTime).getTime() - simpleDateFormat.parse(currentTime).getTime();
    if (difference>0) {
        String hms = String.format("%02d:%02d:%02d", millisLeft/(3600*1000),
                            millisLeft/(60*1000) % 60,
                            millisLeft/1000 % 60);
        textView.setText(hms); //setting the remaining time in a textView
    }
}

我每秒调用方法 updateTimeRemaining() 以便 textview 像计时器一样每秒更新一次.我面临的问题是秒值总是返回 0.相反,我希望秒值每秒更新一次,如下所示:

I'm invoking the method updateTimeRemaining() every second so that the textview gets updated every second like a timer. The problem I'm facing is seconds value always returns 0. Instead I would like the seconds value to be updated every second like below:

01:50:45
01:50:44
01:50:43
01:50:42...

推荐答案

你可以使用

difference = simpleDateFormat.parse(endTime).getTime() - new Date().getTime();

代替这些代码行:

String currentTime = simpleDateFormat.format(new Date());
long difference = simpleDateFormat.parse(endTime).getTime() - simpleDateFormat.parse(currentTime).getTime();

这应该可以正常工作.

这篇关于找到两个时间值之间的时间差总是给出“秒"值为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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