开发者

How to do calendar operations in Java GWT? How to add days to a Date?

Since GWT does not prov开发者_JAVA百科ide the GregorianCalendar class, how to do calendar operations on the client?

I have a Date a and I want the Date, which is n days after a.

Examples:

a (2000-01-01) + n (1) -> 2000-01-02
a (2000-01-01) + n (31) -> 2000-02-01


Updated answer for 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.


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.

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.


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 eventually stray by milliseconds on milleniums when we add or drop leap seconds.


I've created a rough implementation that emulates TimeZone, Calendar, and Locale. Feel free to try it out here:

http://code.google.com/p/gwt-calendar-class/downloads/list

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜