确定以毫秒为单位的时间是否在本周内
所以我有一个以毫秒为单位的时间(之前从 System.currentTimeMillis() 获得)保存在一个 long 变量中。我现在需要的是一种方法来确定该时间是否在当前一周内。我需要获得布尔值的结果。最好的方法是什么?
So I have a time in milliseconds (obtained previously from System.currentTimeMillis()) saved in a long variable. What I need now is a way to determine wether that time is within the actual current week or not. I need to obtain the result as a boolean. What would be the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 Joda
之类的操作来检查它是否正确选择了整周
您可以通过执行诸如Which prints
2011 -12-26T00:00:00.000/2012-01-02T00:00:00.000
。向您表明它已正确找到跨越年份边界的星期。请注意,Joda 默认情况下将星期日视为一周的第一天。如果您需要的话,不确定是否可以将其更改为星期一。由于 Joda 对象是不可变的(只有少数情况不是),它们的生命周期通常非常短,并且上述代码中几乎没有性能开销,因为默认 GC 在处理短生命周期对象时非常有效。但你确实获得了巨大的可读性奖励。
With Joda
You can check it picks out the whole week properly by doing something like
Which prints
2011-12-26T00:00:00.000/2012-01-02T00:00:00.000
. Showing you that it has correctly found the week that crosses the year boundary. Note that Joda, by default, considers Sunday to be the first day of a week. Not sure if you can change this to Monday if that's what you need.Since Joda objects are immutable (there a only a few cases which aren't) they are generally very short lived and there is little to no performance overhead in the above code as the default GC is very efficient at dealing with short lived objects. But what you do gain is a massive readability bonus.
如果您必须使用 JavaSE API,我强烈建议您这样做。对于未来的维护者来说,这更容易,他们可能不是真正的 java 人员,并且理解 WEEK_OF_YEAR 字段的噩梦。
If you must use the JavaSE APIs, I would strongly suggest doing it this way. It's easier for future maintainers who may not really be java people and understand the nightmares of the WEEK_OF_YEAR field.
获取本周开始的时间(以毫秒为单位)和下周开始的时间(以毫秒为单位)。然后查看输入时间是否在这两个值之间:
Get the time in milliseconds of the start of the current week, and the time in milliseconds of the start of the following week. Then see if the input time is between these two values: