我需要确定时间戳是否是精确的小时(即它表示没有分钟,秒或毫秒组件的时间) - 仅使用基元。 代码每秒调用几百次,我不想要Calendar或其他对象的开销。
我试过这个但是舍入错误导致比较失败。
float hours = (time / 3600000f); boolean isExactHour = hours == (int)hours;例如,如果time = 1373763600470,则小时= 381601.03125。 该时间戳代表今天格林尼治标准时间01:00:00:000,小时数应为381601。
有什么想法快速简单地做到这一点? 谢谢!
[编辑]
看起来这比第一眼看上去更复杂(什么时候不是?:)
为清楚起见,我不关心时区,也不关心闰秒。 时间戳由一种方法生成,该方法返回前一个午夜 - 即2013年7月13日00:00:00:000。 我正在计算,对于长数组中的任何时间戳,总是这个初始时间戳加上/减去5分钟的精确倍数。 我的目的是确定一个给定的邮票是否是“最重要的时刻”。 我可能会遇到边缘情况,其中5分钟的倍数与年末重叠,但我可以忍受这些。
I need to determine if a time stamp is an exact hour (i.e. it represents a time with no minutes, seconds or milliseconds components) - using primitives only. The code is called several hundred times per second and I don't want the overhead of a Calendar or other object.
I've tried this but rounding errors cause the comparison to fail.
float hours = (time / 3600000f); boolean isExactHour = hours == (int)hours;For example, if time = 1373763600470, hours = 381601.03125. That time stamp represents 01:00:00:000 GMT today and hours should be 381601.
Any ideas for a quick and simple way to do this? Thanks!
[EDIT]
It seems that this is more complex than at first sight (when is it not? :)
For clarity, I don't care about time zones, nor leap seconds. The time stamp is generated by a method which returns the previous midnight - i.e. 13 July 2013 00:00:00:000 for today. I am then calculating, for any time stamp in an array of longs which is always this initial time stamp plus/minus an exact multiple of 5 minutes. My aim to to determine if a given stamp is "top of the hour". I might have edge cases where the multiple of 5 minutes overlaps a year end but I can live with those.
最满意答案
(time % 36000000) == 0当然这很明显?
编辑
为了获得闰秒的准确性,假设一个自1970年以来以年为索引的闰秒查找表,类似于:
((time-leapSeconds[(int)(time/(1000*60*60*24*365.2425))-1970]*1000) % 3600000) == 0需要这种精确度的程序员也应该看到以下所有Einar的评论。
(time % 36000000) == 0Surely this is obvious?
EDIT
To get accuracy w.r.t. leap seconds, assuming a lookup table of leap seconds indexed by year since (say) 1970, something like:
((time-leapSeconds[(int)(time/(1000*60*60*24*365.2425))-1970]*1000) % 3600000) == 0Programmers needing this level of accuracy should also see all of Einar's comments below.
更多推荐
发布评论