java - 使用 GWT 计算负日期

标签 java gwt

这是我尝试为 GWT 执行日期减法:

Date from = new Date();
Date to = new Date();

    if(filter.equals(DATE_FILTER.PAST_HOUR)){
        minusHoursToDate(to, 1);
    } else if(filter.equals(DATE_FILTER.PAST_24_HOURS)){
        minusHoursToDate(to, 1 * 24);
    } else if(filter.equals(DATE_FILTER.PAST_WEEK)){
        minusHoursToDate(to, 1 * 24 * 7);
    } else if(filter.equals(DATE_FILTER.PAST_MONTH)){
        minusHoursToDate(to, 1 * 24 * 7 * 4);
    } else if(filter.equals(DATE_FILTER.PAST_YEAR)){
        minusHoursToDate(to, 1 * 24 * 7 * 4 * 12);
    }

public static void minusHoursToDate(Date date, int hours){
    date.setTime(date.getTime() - (hours * 3600000));
}

我在这里看到的问题是按月份和年份进行计算。由于月份并不总是按 4 周对齐,并且一年也会受到影响。 减去月份和年份的最佳计算方式是什么?

最佳答案

由于 java.util.Calendar 在 GWT 中不受支持,因为其实现所需的复杂性、最终的 JS 大小等,我会选择一个基于 JS 的简单且轻量级的解决方案。

除了 java Date 实现之外,在 GWT 中,我们还有 JsDate 包装器,其中包括 native JS 日期中可用的所有方法,因此可以减去一个月或一年应该更简单:

    int months = -2;
    int years = -3;
    JsDate j = JsDate.create(new Date().getTime());
    j.setMonth(j.getMonth() + months);
    j.setFullYear(j.getFullYear() + years);
    Date d = new Date((long)j.getTime()); 

您可以执行相同的操作来操纵其他单位:

    getDate()   Returns the day of the month (from 1-31)
    getDay()    Returns the day of the week (from 0-6)
    getFullYear()   Returns the year (four digits)
    getHours()  Returns the hour (from 0-23)
    getMilliseconds()   Returns the milliseconds (from 0-999)
    getMinutes()    Returns the minutes (from 0-59)
    getMonth()  Returns the month (from 0-11)
    getSeconds()    Returns the seconds (from 0-59)

关于java - 使用 GWT 计算负日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28824077/

相关文章:

java - 仅在子类上为列添加唯一约束

java - Spring JPA数据,具有相同功能的多种方法

java - 打印数组的反转时出现 ArrayIndexOutOfBoundsException

GWT 无法将背景图像添加到简单面板

html - 如何编辑 DisclosurePanel 标题的颜色

gwt - 如何找到 GWT 排列的根本原因

java - 当使用 for 循环而不是 Iterator 迭代 ArrayList 时,为什么输出引用的是地址而不是实际对象?

gwt - war 文件中的 Maven Artifact 版本号

java - 如何@Override Comparator使CellTable中的列基于整数而不是基于字符串(GWT)排序?

java - GWT 中的基本面板嵌套