gpt4 book ai didi

objective-c - 如何在 NSDate 上设置时间?

转载 作者:太空狗 更新时间:2023-10-30 03:29:55 26 4
gpt4 key购买 nike

我想将 NSDate 时间设置为我想要的小时:分钟:秒目前我正在使用 NSDate 组件,但它没有给出预期的结果

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

最佳答案

这作为 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];
}

关于objective-c - 如何在 NSDate 上设置时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7288671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com