[英]Get time difference java.sql.Time
I'm trying to get the time differente between two Time vars like this 我试图像这样获取两个时间变量之间的时差
long timeDiffLong = hFim.getTime() - hInic.getTime();
Time timeDiff = new Time(timeDiffLong);
The output is comming something like this 输出正在这样的事情
hFim = 17:30:00
hInic = 17:00:00
timeDiff = 20:30:00
instead of just showing 00:30:00 i always get 20h plus the result 而不是只显示00:30:00我总是得到20小时加上结果
By doing this 通过做这个
Time timeDiff = new Time(timeDiffLong);
you create a new time object, with timeDiffLong
being the milliseconds since 1970-01-01 00:00 UTC. 您创建了一个新的时间对象,
timeDiffLong
是自1970-01-01 00:00 UTC以来的毫秒数。 Since the difference is 30 minutes, the Time
object will refer to 1970-01-01 00:30 UTC. 由于时差为30分钟,因此
Time
对象将参考1970-01-01 00:30 UTC。 But here comes the catch: timeDiff.toString()
will output the time in the default time zone, that is, in most cases the time zone where you are currently are. 但是这里有个问题:
timeDiff.toString()
将输出默认时区中的时间,即,在大多数情况下,您当前所在的时区。
Long story short: Do not force an interval (duration, time difference) into a Time
object. 长话短说:不要将间隔(持续时间,时差)强加到
Time
对象中。 Either use a Duration
class (Joda has one) or just do the division and modulo calculations yourself, as proposed by Kushan. 按照Kushan的建议,要么使用
Duration
类(Joda有一个),要么自己做除法和模运算。
If you use Java 8, you can do: 如果您使用Java 8,则可以执行以下操作:
LocalTime from = hFim.toLocalTime();
LocalTime to = hInic.toLocalTime();
Duration d = Duration.between(from, to);
You can then query the hour/minute etc. with eg d.toMinutes()
. 然后,您可以使用
d.toMinutes()
查询小时/分钟等。
Looks like a duplicated question, have you seen already this answer? 看起来像一个重复的问题,您已经看到这个答案了吗?
How to find difference between two Joda-Time DateTimes in minutes 如何以分钟为单位查找两个Joda-Time DateTime之间的差异
You should take a look at Joda time: 您应该看一下Joda时间:
http://www.joda.org/joda-time/ http://www.joda.org/joda-time/
Your problem is that when you create the time diff with 您的问题是,当您使用
Time timeDiff = new Time(timeDiffLong);
and output that with System.out.println(timeDiff)
then the result is shown for your local time zone . 并使用
System.out.println(timeDiff)
输出,然后显示您当地时区的结果 。 You can see that when you do this: 您可以在执行以下操作时看到:
System.out.println(new Time(0));
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
System.out.println(new Time(0));
That produces the following output here 在这里产生以下输出
00:00:00 //will probably be 20:00:00 for you
16:00:00
In short: Your time difference is shown as a GMT date converted to your local time zone and that is why its several hours off. 简而言之:您的时差显示为格林尼治标准时间(GMT)日期,已转换为您当地的时区,因此这就是几个小时的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.