Rounding an NSDate to the nearest start and and of day
There are times when you want to round a date to the nearest beginning or end of a day. Here is how that is done.
First, this will round to the start of the day (note I have defined minimumDate as a property of my class)
//First set the unit flags you want automatically put into your date from an NSDate object
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
//now create an NSCalendar object
NSCalendar *cal = [NSCalendar currentCalendar];
//Use the NSCalendar object to create an NSDateComponents object from the date you are interested in rounding
//In this case we are just using the time now by calling [NSDate date]
NSDateComponents *minDateComps = [cal components:unitFlags fromDate:[NSDate date]];
//Now we use the NSCalendar object again to generate a date from the date components object
self.minimumDate = [cal dateFromComponents:minDateComps];
Now, lets round to the end of the day. It is basically the same but we need to set the hours, minutes and seconds
//First set the unit flags you want automatically put into your date from an NSDate object
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
//now create an NSCalendar object
NSCalendar *cal = [NSCalendar currentCalendar];
//Use the NSCalendar object to create an NSDateComponents object from the date you are interested in rounding
//In this case we are just using the time now by calling [NSDate date]
NSDateComponents *maxDateComps = [cal components:unitFlags fromDate:[NSDate date]];
//now set the hours, minutes and seconds to the end of the day
maxDateComps.hour = 23;
maxDateComps.minute = 59;
maxDateComps.second = 59;
//Now we use the NSCalendar object again to generate a date from the date components object
self.maximumDate = [cal dateFromComponents:maxDateComps];
That is all there is to it. This can easily be extended to round to the nearest hour, minute or second. I will leave that exercise to the reader.
Bruce Truax
Diffraction Limited Design LLC
|