Re: Good and handy NSTimestamp utilites...
Re: Good and handy NSTimestamp utilites...
- Subject: Re: Good and handy NSTimestamp utilites...
- From: Francis Labrie <email@hidden>
- Date: Mon, 31 Oct 2005 18:59:17 -0500
Le 03 oct. 2005, à 04:32, email@hidden a écrit :
/** Adds time to a date.<BR>
* This utility method replaces NSTimestamp.
* timestampByAddingGregorianUnits() which does all its computations in the
* GMT timezone. This leads to several problems. For one DST changes don't
* happen as expected. Adding 1 month to a CET midnight of a first of a
* month does not bring us to the first of the next month, but only as many
* days further as there are days in the preceeding month.
*
[...]
**/
public static NSTimestamp timestampByAddingGregorianUnits(
Date date,
int year,
int month,
int day,
int hour,
int minute,
int second)
{
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date);
return new NSTimestamp(
calendar.get(GregorianCalendar.YEAR) + year,
calendar.get(GregorianCalendar.MONTH) + month + 1,
calendar.get(GregorianCalendar.DAY_OF_MONTH) + day,
calendar.get(GregorianCalendar.HOUR_OF_DAY) + hour,
calendar.get(GregorianCalendar.MINUTE) + minute,
calendar.get(GregorianCalendar.SECOND) + second,
NSTimeZone.getDefault());
}
Unfortunately, this methode doesn't preserve milliseconds:
dateB = timestampByAddingGregorianUnits(dateA, 0, 0, 0, 1, 0, 0);
dateB = timestampByAddingGregorianUnits(dateB, 0, 0, 0, -1, 0, 0);
After this,
dateA.equals(dateB) will return
false in most cases.
To fix this, you can replace the body of the method with this code:
{
Calendar calendar;
calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, year);
calendar.add(Calendar.MONTH, month);
calendar.add(Calendar.DAY_OF_MONTH, day);
calendar.add(Calendar.HOUR_OF_DAY, hour);,
calendar.add(Calendar.MINUTE, minute);
calendar.add(Calendar.SECOND, second);
return(new NSTimestamp(calendar.getTime()));
}
--
<x-tad-bigger>Francis Labrie</x-tad-bigger>
Saint-Bruno-de-Montarville, Quebec, Canada
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Webobjects-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden