How to set time on NSDate?

Mubashir Hassan Khan picture Mubashir Hassan Khan · Sep 2, 2011 · Viewed 20.2k times · Source

I want to set the NSDate time with my desired hours:minutes:seconds currently im working with NSDate component but it is not giving the desired result

[comps setHour: -hours];
[comps setMinute:0];
[comps setSecond:0];
NSDate *minDate = [calendar_c dateFromComponents:comps];

Answer

memmons picture memmons · Aug 14, 2013

This works great as an NSDate category.

/** 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;
}

With the above category, if you have an existing date you want to change the time on, you do so like this:

NSDate *newDate = [someDate dateWithHour:10 minute:30 second:00];

If, however, you are trying to add or subtract hours from an existing date, a category method to do that is also straightforward:

/** 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];
}