commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Stephen Colebourne" <scolebou...@btopenworld.com>
Subject Re: [lang] possible DateUtils method
Date Mon, 24 Nov 2003 23:11:38 GMT
I think this would make a good addition to DateUtils. Would you like to
provide a patch and tests?

Stephen

----- Original Message -----
From: "Inger, Matthew" <inger@Synygy.com>
> public static final long MILLIS_IN_DAY = 1000*60*60*24;
>
> public long getDaysBetween(Calendar c1, Calendar c2)
> {
> long c1Normalized = c1.getTime().getTime() +
>                           c1.get(Calendar.ZONE_OFFSET) +
>                           c1.get(Calendar.DST_OFFSET);
>
> long c2Normalized = c2.getTime().getTime() +
>                           c2.get(Calendar.ZONE_OFFSET) +
>                           c2.get(Calendar.DST_OFFSET);
>
> long diff = c1Normalized - c2Normalized;
>
> long numDays = diff / MILLIS_IN_DAY;
>
> return numDays;
> }
>
> A common mistake most people make is to ignore daylight savings
> time when trying to compute the number of days between two Calendar
> dates.  If you cross the DST boundary when the clock jumps forward,
> just subtracting the date objects and dividing will end up giving you
> an answer that is off by 1 day.  This happens because the clock jumps
> ahead, and 00:00 EDT is actually 11:00 EST on the previous day, so the
> number of hours is off by 1, and thus the calculation doesn't end up
working
> properly.  The other thing i'm doing here is to convert to GMT time,
> allowing
> for the two Calendar objects to have different timezones.
>
> We could have similar methods for getHoursBetween and so forth.  Months
> would be a bit more complicated of an algorithm.
>


---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message