java - java.util.Date 的 .after() 的精确度如何

标签 java date gwt

我在 Smart GWT 应用程序中使用日期验证,其中有两个字段 fromDatetoDate,of DateItem 每当用户选择 future 日期时,它都会显示一条错误消息,我使用了 java.util.Date 类的 .after() 方法。

现在,我的问题是 .after() 比较日期还是也比较时间。 Date 类的 .after().before() 方法的精确度如何?

最佳答案

快速回答:

它肯定还会比较时间(可能精度约为 1-20 毫秒)。

详细信息:

看看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() 函数直接映射到两个 getTime() 之间的比较。调用底层 JavaScript 日期对象。由于 JavaScript 的 getTime() 返回以毫秒为单位的时间,因此这是您在 GWT 中可以期望的最佳精度。现在,我不知道是否所有浏览器实际上都以毫秒级别报告时间,或者即使所有浏览器都以相同的精度报告时间,但如果我正确理解您的问题,您只担心日期与时间。所以,为了回答这个问题,它确实也比较了时间,我想说你应该总是能够期望比 1 秒好得多的精度,可能在 1 毫秒到 20 毫秒左右。

如果您只想检查日精度,则必须比较 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 尚未实现日历。

关于java - java.util.Date 的 .after() 的精确度如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216126/

相关文章:

java - 无法在 GWT 中取消重复计时器

java - 具有不同列数的 Hibernate 多对一映射

java - Primefaces InputSwitch 组件在 Ajax 请求后复制

java - 远程调用同一服务器上存在的 EJB 时出现 ClassCastException

python - 将长字符串解析为日期时间

Java 验证日期条目

Mysql 间隔新年后不起作用

java - xml dom 解析器然后用 ListView 显示结果

security - 更多 GWT 和 Tomcat 6 安全问题 (windows)

php - 我应该用什么编写Web应用程序?它需要能够查询SQL数据库和LDAP数据库