Android Java:如何相减两次? [英] Android Java : How to subtract two times?

查看:79
本文介绍了Android Java:如何相减两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用了某种秒表,并且有

I use some kind of stopwatch in my project and I have

start time ex: 18:40:10 h
stop time  ex: 19:05:15 h

我需要这两个值的结果,例如final time = stop - start

I need a result from those two values like final time = stop - start

我找到了一些示例,但它们都非常令人困惑.

I found some examples but they all are very confusing .

有什么简单的解决方法吗?

Is there any simple solution ?

推荐答案

如果您有字符串,则需要使用java.text.SimpleDateFormat将其解析为java.util.Date.像这样:

If you have strings you need to parse them into a java.util.Date using java.text.SimpleDateFormat. Something like:

        java.text.DateFormat df = new java.text.SimpleDateFormat("hh:mm:ss");
        java.util.Date date1 = df.parse("18:40:10");
        java.util.Date date2 = df.parse("19:05:15");
        long diff = date2.getTime() - date1.getTime();

这里的差异是18:40:10到19:05:15之间经过的毫秒数.

Here diff is the number of milliseconds elapsed between 18:40:10 and 19:05:15.

为此找到了一种在线方法(位于

Found a method online for this (at http://www.javaworld.com/javaworld/jw-03-2001/jw-0330-time.html?page=2):

  int timeInSeconds = diff / 1000;
  int hours, minutes, seconds;
  hours = timeInSeconds / 3600;
  timeInSeconds = timeInSeconds - (hours * 3600);
  minutes = timeInSeconds / 60;
  timeInSeconds = timeInSeconds - (minutes * 60);
  seconds = timeInSeconds;

如果您希望将其作为字符串(这是一种草率的方式,但是可以使用):

If you want it as a string (this is a sloppy way, but it works):

String diffTime = (hours<10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds) + " h";

如果要毫秒,就这样做

long timeMS = diff % 1000;

然后可以将其除以1000,得到秒的小数部分.

You can then divide that by 1000 to get the fractional part of your seconds.

这篇关于Android Java:如何相减两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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