对 Date 对象使用 Groovy 比较运算符
我正在调查一个问题,并遇到一些可疑代码,涉及使用比较运算符比较日期实例。例如
def stamp = ... //Date
def offset = ... //Integer
def d = new Date(stamp.time + offset)
if (d < new Date()) {
...
}
This 资源表明上述内容等效于以下内容
def stamp = ... //Date
def offset = ... //Integer
def d = new Date(stamp.time + offset)
if (d.compareTo(new Date()) < 0) {
...
}
但是, 关于日期的 GDK 文档仅包含使用 compareTo
比较日期的示例,< code>before 和 after
我似乎记得特别避免在日期上使用比较运算符,因为有过意外结果的经历。上述两个代码示例是否确实等效(也就是说,我可以安全地在 Groovy 中的日期上使用比较运算符,还是应该只使用 compareTo
、before
和 之后)?
谢谢!
I'm investigating an issue and ran across some suspicious code involving comparison of Date instances using comparison operators. e.g.
def stamp = ... //Date
def offset = ... //Integer
def d = new Date(stamp.time + offset)
if (d < new Date()) {
...
}
This resource indicates the above is equivalent to the following
def stamp = ... //Date
def offset = ... //Integer
def d = new Date(stamp.time + offset)
if (d.compareTo(new Date()) < 0) {
...
}
However, the GDK documentation on Dates only has examples comparing dates using compareTo
, before
, and after
and I seem to recall specifically avoiding using the comparison operators on Dates due to an experience with unexpected results. Are the above two code examples indeed equivalent (that is, can I safely use comparison operators on Dates in Groovy, or should I only use compareTo
, before
, and after
)?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将它们插入方便的 GroovyConsole,它们会得到相同的结果。
如果我正确理解了这个问题:
打印“之前”两次
如果我将邮票日期切换到 2011 年,可以说它不会打印。
Well if you plug them into the handy GroovyConsole they have the same result.
If I understand the question correctly:
Prints "before" twice
If I switched the stamp date to 2011 lets say it would not print.