如何使用Cocoa获取当前时间?

ksn*_*snr 4 cocoa objective-c

如何使用Objective-C获取Cocoa中的当前小时?

Jas*_*oco 39

首先,您应该阅读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];
}
Run Code Online (Sandbox Code Playgroud)


and*_*ndi 6

一种方法是使用NSCalendar和NSDateComponents

NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSHourCalendarUnit fromDate:now];
NSInteger hour = [components hour];
Run Code Online (Sandbox Code Playgroud)