markdorison markdorison - 1 year ago 42
Objective-C Question

How can I get an NSDate object for today at midnight?

What is the most efficient way to obtain an NSDate object that represents midnight of the current day?

Answer Source

Try this:

NSDate *const date =;
NSCalendar *const calendar = NSCalendar.currentCalendar;
NSCalendarUnit const preservedComponents = (NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay);
NSDateComponents *const components = [calendar components:preservedComponents fromDate:date];
NSDate *const normalizedDate = [calendar dateFromComponents:components];