gpt4 book ai didi

java - 安卓Java : How to subtract two times?

转载 作者:搜寻专家 更新时间:2023-10-30 21:14:19 25 4
gpt4 key购买 nike

我在我的项目中使用了某种秒表

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

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

我找到了一些例子,但它们都很困惑。

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

最佳答案

如果您有字符串,则需要使用 java.text.SimpleDateFormat 将它们解析为 java.util.Date。像这样的东西:

        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 之间经过的毫秒数。

编辑 1:

在网上找到了一个方法(在 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;

编辑 2:

如果你想要它作为一个字符串(这是一种草率的方式,但它有效):

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

编辑 3:

如果你想要毫秒就这样做

long timeMS = diff % 1000;

然后您可以将其除以 1000 以获得秒数的小数部分。

关于java - 安卓Java : How to subtract two times?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3514639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com