问题描述
我在我的项目中使用了某种秒表并且我有
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();
这里的 diff 是 18:40:10 和 19:05:15 之间经过的毫秒数.
Here diff is the number of milliseconds elapsed between 18:40:10 and 19:05:15.
编辑 1:
在网上找到了一个方法(在 http://www.javaworld/javaworld/jw-03-2001/jw-0330-time.html?page=2):
Found a method online for this (at http://www.javaworld/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;
编辑 2:
如果你想要它作为一个字符串(这是一种草率的方式,但它有效):
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";
编辑 3:
如果你想要毫秒就这样做
If you want the milliseconds just do this
long timeMS = diff % 1000;
然后您可以将其除以 1000 以获得秒的小数部分.
You can then divide that by 1000 to get the fractional part of your seconds.
这篇关于Android Java:如何减去两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论