我在Smart GWT应用程序中使用日期验证,其中有fromDate
和toDate
两个字段DateItem
每当用户选择将来的日期时,它都会显示一条错误消息,我使用了java.util.Date类的.after()
方法。
现在,我的问题是.after()比较一天或者它也比较时间。
Date类的.after()
和.before()
方法有多精确?
答案 0 :(得分:2)
快速回答:
它肯定也比较了时间(可能是大约1-20ms的准确度)。
<强>详细信息:强>
查看GWT source code for the Date implementation可以回答您的问题:
public boolean after(Date when) {
return getTime() > when.getTime();
}
public boolean before(Date when) {
return getTime() < when.getTime();
}
...
public long getTime() {
return (long) jsdate.getTime();
}
在这里,您可以看到,after()
- 和before()
- 函数直接映射到基础JavaScript日期对象上的两个getTime()
调用之间的比较。由于JavaScript的getTime()
以毫秒为单位返回时间,因此这是您在GWT中可以期望的最佳准确度。现在,我不知道所有浏览器是否确实报告了毫秒级别的时间,或者即使所有浏览器都以相同的准确度报告,但如果我正确理解您的问题,您只会担心日期与时间的关系。所以,为了回答这个问题,它确实比较了时间,我会说你应该总是能够期望比1s更好的准确度,可能大约1ms到20ms。
如果您只想检查日期准确性,则必须比较getYear()
,getMonth()
和getDate()
返回的值(不 getDay()
!!!)你自己,比如说像这样:
public boolean isLaterDay(Date date, Date reference) {
if (date.getYear () > reference.getYear ()) return true;
if (date.getYear () < reference.getYear ()) return false;
if (date.getMonth() > reference.getMonth()) return true;
if (date.getMonth() < reference.getMonth()) return false;
return (date.getDate() > reference.getDate());
}
注意:这个答案专门针对GWT,而不是一般的Java。在普通的Java中,我希望你可能会获得与GWT相同甚至更高的分辨率。但由于我没有源代码,我不确定。此外,getYear()
和此类函数在常规Java中已弃用,不应再在那里使用(而是使用Calendar.get(...)
),但GWT尚未实现日历。