On Jan 4, 2010, at 02:26, Brian Bruinewoud wrote:

> What's the best way to get an NSDate object for 'today' such that the time is 
> 00:00:00 (or any other constant).
> I not interested in the time, I only care about the year-month-day, but I do 
> need the the hours-minutes-seconds to be the same on all dates so that I can 
> compare the dates.
> 
> Currently I do this:
> 
>    NSDateFormatter *dateFmter = [[NSDateFormatter alloc] init];
>    [dateFmter setTimeStyle:NSDateFormatterNoStyle];
>    [dateFmter setDateStyle:NSDateFormatterMediumStyle];
> 
>    NSString dateText = [ dateFmter stringFromDate: self.now ]; // !! !! I 
> need dateText anyway
> 
>    self.now = [ dateFmter dateFromString: dateText ]; // !! truncate time to 
> 00:00:00
> 
> But this seems ugly, cumbersome and inefficient.
> 
> The other option might be to use NSDate, NSCalendar and NSDateComponents, but 
> that seems to be even more ugly and cumbersome and probably more inefficient.

NSDate is *not* a good choice for these sorts of comparisons, because it's 
always a date and a time, and it's not as simple as it seems. Consider this 
(unlikely) example:

Suppose you decided to force the time to 2:30 am instead of midnight. Probably 
doesn't behave as expected on days of daylight savings changeover (in places 
when it changes at 2 am), where they might be no 2:30 am, or two of them. Also, 
the difference between two dates "standardized" like that is not necessarily 
exactly one day, so computing elapsed days can be problematic too.

If you only need to compare dates, you could certainly do it if you could 
standardize each NSDate to a unique time on that date, but choosing the time -- 
and standardizing to it -- is not easy unless you assume knowledge about how 
NSDate is implemented.

The correct solution is NSDateComponents. It's slightly bulkier but correct.


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to