Android Java:如何减去两次?
我在我的项目中使用某种秒表,我需要
start time ex: 18:40:10 h
stop time ex: 19:05:15 h
这两个值的结果,例如final time = stop - start
我找到了一些示例,但它们都非常令人困惑。
有什么简单的解决办法吗?
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
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您有字符串,则需要使用 java.text.SimpleDateFormat 将它们解析为 java.util.Date。类似于:
这里 diff 是 18:40:10 和 19:05:15 之间经过的毫秒数。
编辑1:
在网上找到了一个方法(位于 http://www.javaworld.com/javaworld/jw-03-2001/jw-0330-time.html?page=2):
编辑2:
如果你想要它作为一个字符串(这是一种草率的方式,但它有效):
编辑3:
如果你想要毫秒,就这样做
你可以将其除以1000以获得秒的小数部分。
If you have strings you need to parse them into a java.util.Date using java.text.SimpleDateFormat. Something like:
Here diff is the number of milliseconds elapsed between 18:40:10 and 19:05:15.
EDIT 1:
Found a method online for this (at http://www.javaworld.com/javaworld/jw-03-2001/jw-0330-time.html?page=2):
EDIT 2:
If you want it as a string (this is a sloppy way, but it works):
EDIT 3:
If you want the milliseconds just do this
You can then divide that by 1000 to get the fractional part of your seconds.
假设您正在使用 java.util.Date:
结果将以毫秒为单位的总时间。
Assuming you are using java.util.Date:
The result will be the total time in milliseconds.
我正在提供现代答案。
java.time 和 ThreeTenABP
此示例的输出为:
其他答案在 2010 年都是很好的答案。今天避免使用
DateFormat
、SimpleDateFormat
和Date
类。 java.time,现代 Java 日期和时间 API,使用起来要好得多。但它不需要 API 级别 26 吗?
不,使用 java.time 在旧版和新版 Android 设备上都能很好地工作。它只需要至少 Java 6。
链接
java.time< /code> 首次被描述。
java.time
向后移植到 Java 6 和7(JSR-310 为 ThreeTen)。I am providing the modern answer.
java.time and ThreeTenABP
Output from this example is:
The other answers were good answers in 2010. Today avoid the classes
DateFormat
,SimpleDateFormat
andDate
. java.time, the modern Java date and time API, is so much nicer to work with.But doesn’t it require API level 26?
No, using java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.Links
java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).尝试这个答案,它会对您有很大帮助,
此处
在这个答案中,您会发现减去两次丢弃日期和月份和年份。
它给出了达到第二个时间值之前将花费的分钟数。
Try this answer it will help you a lot
from here
In this answer, you will find subtract to two times discarding the day and month and year.
it gives you the number of minutes you will spend until you reach the second Time value.
如今,有了较新的 Java(不知道在什么 Android 版本上可以使用):
过去笨拙的 Java 方式现在已经不复存在了。
Today, with newer Java (no idea, at what Android version this works):
The clumsy java ways from olden days are now gone.