【问题标题】:getting current hour, minutes and seconds in iPhone在 iPhone 中获取当前的小时、分钟和秒
【发布时间】:2011-01-22 14:19:12
【问题描述】:

如何从中获取当前的小时、分钟和秒?

NSDate *now = [NSDate date];

谢谢!我想要 3 个 int 变量,其中存储了值,而不是显示值的字符串。

【问题讨论】:

    标签: iphone datetime time timezone timestamp


    【解决方案1】:

    您需要使用NSDateComponents,这有点棘手(更不用说冗长了!),因为您需要了解一点 Cocoa 处理日历的方式。 docs 中有很棒的介绍;这是修改后的摘录:

    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components =
                        [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:today];
    
    NSInteger hour = [components hour];
    NSInteger minute = [components minute];
    NSInteger second = [components second];
    

    【讨论】:

    • [gregorian autorelease] 肯定在最后,防止内存泄漏
    • autorelease、NSHourCalendarUnit、NSMinuteCalendarUnit 和 NSSecondCalendarUnit 都已弃用。
    猜你喜欢
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多