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

后端 未结 4 979
一整个雨季
一整个雨季 2020-12-05 12:53

Since GWT does not provide the GregorianCalendar class, how to do calendar operations on the client?

I have a Date a and I want the Date, which is

相关标签:
4条回答
  • 2020-12-05 13:14
    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.

    0 讨论(0)
  • 2020-12-05 13:19

    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 讨论(0)
  • 2020-12-05 13:28

    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.

    0 讨论(0)
  • 2020-12-05 13:36

    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.

    0 讨论(0)
提交回复
热议问题