यह NSDate
श्रेणी के रूप में बहुत अच्छा काम करता है।
/** 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;
}
ऊपर श्रेणी के साथ
, अगर आप आप पर समय को बदलना चाहते हैं एक मौजूदा तिथि होती है, आप इस तरह ऐसा:
NSDate *newDate = [someDate dateWithHour:10 minute:30 second:00];
अगर, हालांकि, आप जोड़ने का प्रयास कर रहे हैं या एक मौजूदा तारीख से घंटे घटाना, ऐसा करने के लिए एक वर्ग विधि भी स्पष्ट है:
/** 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];
}
NSDate समय में एक असली तारीख प्रतिनिधित्व करने के लिए बनाया गया है। क्या आप वास्तविक घटकों के लिए समय घटकों को सेट करने की कोशिश कर रहे हैं? –