NSDate without time portion

The Problem

Sometimes you need to make comparation with dates, but NSDate is not actually a Date like YYYYMMDD. In fact NSDate conceptually store time relative to Jan 1, 2001, GMT. So if you get a [NSDate date] and two seconds after you get another [NSDate date] you will have two different dates.

The Solution, well… One solution of many

One way to solve this problem is to set the time portion of NSDate to a arbitrary value like 00:00:00. To do this take a look in the code that follows:

+(NSDate *) normalizedDate {
 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 // [gregorian setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
 [gregorian setTimeZone:[NSTimeZone localTimeZone]];

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit | kCFCalendarUnitWeekday | kCFCalendarUnitWeekdayOrdinal fromDate:[NSDate date]];

NSDateComponents *normalized = NSDateComponents.alloc.init;
 [normalized setWeekday: [components weekday]];
 [normalized setWeekdayOrdinal:[components weekdayOrdinal]];
 [normalized setMonth:[components month]];
 [normalized setYear:[components year]];

return [gregorian dateFromComponents:normalized];

In some situations you will want to set a specific time zone, to do so I suggest you to put time zone at “GMT” as the comented part of the code above.

0 Responses to “NSDate without time portion”

Comments are currently closed.

Premium Wordpress Plugin