How to do calendar operations in Java GWT? How to add days to a Date?
Solution 1
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.
Solution 2
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.
Solution 3
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.
Solution 4
I've created a rough implementation that emulates TimeZone, Calendar, and Locale. Feel free to try it out here:
Witek
Updated on June 26, 2020Comments
-
Witek almost 4 years
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 isn
days aftera
.Examples:
a (2000-01-01) + n (1) -> 2000-01-02 a (2000-01-01) + n (31) -> 2000-02-01
-
Chris Lercher over 13 years+1, but please note: It depends very much on what you want to achieve. Usually, adding 7 days to "2011-03-22 10:00:00 CET" should result in "2011-03-29 10:00:00 CET" (i.e. the local time should stay at 10 o'clock). But because in CET, a clock change (DST) occurs between the two dates, the millisecond calculation will yield a different result. Again, it depends on what kind of calculation you want!
-
cellepo over 9 yearsThe alternative answer by @Chris Lercher can help if you need to add a unit of time besides Days (i.e: hours)
-
cellepo over 9 yearsYou can similarly call Date's other set methods for adding different units of time (i.e: setHours)
-
Alex K. over 2 yearsThis fails for daylight saving. Over a daylight savings night, adding 24 hours is not the same as adding 1 day.