Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This works great as an <code>NSDate</code> category.</p> <pre><code>/** Returns a new NSDate object with the time set to the indicated hour, * minute, and second. * @param hour The hour to use in the new date. * @param minute The number of minutes to use in the new date. * @param second The number of seconds to use in the new date. */ -(NSDate *) dateWithHour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second { NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [calendar components: NSYearCalendarUnit| NSMonthCalendarUnit| NSDayCalendarUnit fromDate:self]; [components setHour:hour]; [components setMinute:minute]; [components setSecond:second]; NSDate *newDate = [calendar dateFromComponents:components]; return newDate; } </code></pre> <p>With the above category, if you have an existing date you want to change the time on, you do so like this:</p> <p><code>NSDate *newDate = [someDate dateWithHour:10 minute:30 second:00];</code></p> <p>If, however, you are trying to add or subtract hours from an existing date, a category method to do that is also straightforward:</p> <pre><code>/** Returns a new date with the given number of hours added or subtracted. * @param hours The number of hours to add or subtract from the date. */ -(NSDate*)dateByAddingHours:(NSInteger)hours { NSDateComponents *components = [[NSDateComponents alloc] init]; [components setHour:hours]; return [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:self options:0]; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload