How round an NSDate to midnight (00:00) of the day?

NSDate* now = [NSDate date];
// How get midnight time of now?
Answered by DTS Engineer in 792443022

Ah, um, what about the startOfDay(for:) method?

Keep in mind that the start of the day may not be midnight. Some time zones do daylight saving time switches at midnight, which means that midnight might not be a valid time in that time zone.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

Something like this should work:

-(NSDate *)startOfDay:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    return [cal dateFromComponents:components];
}

Ah, um, what about the startOfDay(for:) method?

Keep in mind that the start of the day may not be midnight. Some time zones do daylight saving time switches at midnight, which means that midnight might not be a valid time in that time zone.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How round an NSDate to midnight (00:00) of the day?
 
 
Q