Benjamin Benjamin - 1 year ago 107
Objective-C Question

Truncate NSDate (Zero-out time)

I want to generate a new

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

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


2010-10-30 10:14:13 GMT

2010-10-30 00:00:00 GMT

Answer Source
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).


To take time zone into account:

NSDate* dateOnly = [[calendar dateFromComponents:components] dateByAddingTimeInterval:[[NSTimeZone localTimeZone]secondsFromGMT]];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download