Benjamin Benjamin - 2 months ago 9
Objective-C Question

Truncate NSDate (Zero-out time)

I want to generate a new

NSDate
with 0 hours, 0 minutes, and 0 seconds for time. The source date can be any random
NSDate
.

Is there a way to achieve this? The documentation did not help me with this.




Example

Have:
2010-10-30 10:14:13 GMT


Want:
2010-10-30 00:00:00 GMT

Answer
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];

date is the date you want to remove the time from.

This separates the date and time and creates a new date with the default time (00:00:00).

EDIT

To take time zone into account:

NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];