如何在 Java GWT 中进行日历操作?如何在日期中添加天数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2527845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do calendar operations in Java GWT? How to add days to a Date?
提问by Witek
Since GWT does not provide the GregorianCalendar class, how to do calendar operations on the client?
由于GWT没有提供GregorianCalendar类,那么如何在客户端做日历操作呢?
I have a Date a
and I want the Date, which is n
days after a
.
我有一个日期a
,我想日期,这是n
几天之后a
。
Examples:
例子:
a (2000-01-01) + n (1) -> 2000-01-02
a (2000-01-01) + n (31) -> 2000-02-01
采纳答案by Tony BenBrahim
Updated answer for GWT 2.1
GWT 2.1 的更新答案
final Date dueDate = new Date();
CalendarUtil.addDaysToDate(dueDate, 21);
Edit: the fully qualified name of this class is com.google.gwt.user.datepicker.client.CalendarUtil.
编辑:此类的完全限定名称是com.google.gwt.user.datepicker.client.CalendarUtil。
回答by Chris Lercher
The answer that Google seems to use (currently), is:
谷歌似乎(目前)使用的答案是:
@SuppressWarnings("deprecation") // GWT requires Date
public static void addDaysToDate(Date date, int days) {
date.setDate(date.getDate() + days);
}
This is from the class com.google.gwt.user.datepicker.client.CalendarUtil
, which is used by com.google.gwt.user.datepicker.client.DatePicker
. I imagine, that there will be problems involved, when doing calculations in different timezones.
这是来自类com.google.gwt.user.datepicker.client.CalendarUtil
,由com.google.gwt.user.datepicker.client.DatePicker
. 我想,在不同的时区进行计算时会涉及到问题。
Lots of people have already voted for some kind of Joda time for GWT: http://code.google.com/p/google-web-toolkit/issues/detail?id=603. The currently last comment states, that there's a new fork of goda time, maybe we should really check it out.
很多人已经为 GWT 投票支持某种 Joda 时间:http: //code.google.com/p/google-web-toolkit/issues/detail? id=603 。当前最后一条评论指出,goda 时间有一个新的分支,也许我们真的应该检查一下。
回答by user471824
I've created a rough implementation that emulates TimeZone, Calendar, and Locale. Feel free to try it out here:
我创建了一个模拟 TimeZone、Calendar 和 Locale 的粗略实现。随意在这里尝试一下:
回答by Norm Wright
private static final long MILLISECONDS_IN_SECOND = 1000l;
private static final long SECONDS_IN_MINUTE = 60l;
private static final long MINUTES_IN_HOUR = 60l;
private static final long HOURS_IN_DAY = 24l;
private static final long MILLISECONDS_IN_DAY = MILLISECONDS_IN_SECOND *
SECONDS_IN_MINUTE *
MINUTES_IN_HOUR *
HOURS_IN_DAY;
public Date addDays (Date date, days)
{
return new Date (date.getTime () + (days * MILLISECONDS_IN_DAY));
}
this will work with leap years but will eventuallystray by milliseconds on milleniums when we add or drop leap seconds.
这将适用于闰年,但当我们添加或删除闰秒时,最终会在千禧年中偏离毫秒。