Search code examples
objective-ccocoa-touchnsdate

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?


Solution

  • 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];