markdorison markdorison - 4 months ago 8
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

Try this:

NSDate *const date = NSDate.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];