这是我尝试为 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/