Android Java:如何减去两次?

编程入门 行业动态 更新时间:2024-10-28 05:20:51
本文介绍了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();

这里的 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:关键词]

本文发布于:2023-03-28 18:23:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/736941.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   Android   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!