Reputation: 413
I frequently use the NSDate compare method - but I want to consider two dates similar if they are equal in year, month, day. I have made a procesure called "cleanDate" to remove the hour part before I compare.
-(NSDate*)cleanDate:(NSDate*)date {
NSCalendarUnit unitflags;
NSDateComponents *component;
NSCalendar *calendar;
calendar=[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
unitflags=NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
component=[calendar components:unitflags fromDate:date];
return [calendar dateFromComponents:component]; //Dato uten klokke
}
But my dates come out as:
2011-10-28 22:00:00 and some dates as: 2011-10-28 23:00:00
I want the hour part to be similar, e.g. 00:00.
Whats wrong? Does it have something to do with daylight saving time? Other? Thanks.
Upvotes: 1
Views: 145
Reputation: 413
Seems like this is a Time Zone issue... I thought NSLog would default to the local time zone - but it seems to default to GMT...
Date with GMT time zone is: Sat, 29 Oct 2011 22:00:00 GMT+00:00
Date with system time zone is: Sun, 30 Oct 2011 00:00:00 GMT+02:00
NSlog shows 2011-10-29 22:00:00 +0000
When using NSLog(@"NSlog shows %@",finalDate); it seems to print the GMT time...
When using this code - I will get the local date in my time zone:
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss z"];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
NSString *dateString = [dateFormatter stringFromDate:myDate];
NSLog(@"Date with system time zone is: %@",dateString);
... so my original cleanDate actually seems to do what I want after all...
Upvotes: 0
Reputation: 3547
-(NSDate*)cleanDate:(NSDate*)date {
NSDateComponents *comps = [[NSCalendar currentCalendar]
components:NSDayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit
fromDate:date];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:[[NSTimeZone systemTimeZone] secondsFromGMT]];
return [[NSCalendar currentCalendar] dateFromComponents:comps];
}
Upvotes: 2