如何使用Objective-C获取Cocoa中的当前小时?
首先,您应该阅读Cocoa的日期和时间编程主题.这将使您很好地理解使用Cocoa中提供的各种日期/时间/日历对象进行日期的高级转换.
但是,此代码片段将回答您的具体问题:
- (NSInteger)currentHour { // In practice, these calls can be combined NSDate *now = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now]; return [components hour]; }
一种方法是使用NSCalendar和NSDateComponents
NSDate *now = [NSDate date]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now]; NSInteger hour = [components hour];