DLD-LLC Discussion Forums
Not logged in [Login - Register]
Go To Bottom

Printable Version | Subscribe | Add to Favorites  
Author: Subject: Rounding an NSDate to the nearest start and and of day
BruceTruax
Super Moderator
*******


Avatar


Posts: 54
Registered: 13-5-2009
Member Is Offline


[*] posted on 23-11-2009 at 05:28 PM
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
View user's profile Visit user's homepage View All Posts By User U2U Member

  Go To Top

Powered by XMB
Developed By The XMB Group © 2001-2008
[Queries: 18] [PHP: 48.9% - SQL: 51.1%]