我如何在 android 中获得两个日期之间的差异?,尝试了所有事情并发布 [英] How do I get difference between two dates in android?, tried every thing and post
问题描述
我看到了这里的所有帖子,但我仍然不知道如何获得两个 android 日期之间的差异.
I saw all the post in here and still I can't figure how do get difference between two android dates.
这就是我所做的:
long diff = date1.getTime() - date2.getTime();
Date diffDate = new Date(diff);
我得到:日期是 1970 年 1 月 1 日,时间总是在两个小时内更大......我来自以色列,所以两个小时是 timeOffset.
and I get: the date is Jan. 1, 1970 and the time is always bigger in two hours...I'm from Israel so the two hours is timeOffset.
我怎样才能得到正常的差异???
How can I get normal difference???
推荐答案
您已经接近正确答案了,这两个日期之间的差异以毫秒为单位,但是当您尝试根据该差异构建日期时,它假设您要创建一个新的 Date
对象,并将该差异值作为其纪元时间.如果您正在寻找以小时为单位的时间,那么您只需对该 diff
进行一些基本算术即可获得不同的时间部分.
You're close to the right answer, you are getting the difference in milliseconds between those two dates, but when you attempt to construct a date out of that difference, it is assuming you want to create a new Date
object with that difference value as its epoch time. If you're looking for a time in hours, then you would simply need to do some basic arithmetic on that diff
to get the different time parts.
Java:
long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
科特林:
val diff: Long = date1.getTime() - date2.getTime()
val seconds = diff / 1000
val minutes = seconds / 60
val hours = minutes / 60
val days = hours / 24
所有这些数学运算都将简单地进行整数运算,因此会截断任何小数点
All of this math will simply do integer arithmetic, so it will truncate any decimal points
这篇关于我如何在 android 中获得两个日期之间的差异?,尝试了所有事情并发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!