获取当前时间

时间:2012-02-16 18:55:49

标签: objective-c ios

我试图获得当前的小时和秒。这是我使用的代码

NSDate *now = [NSDate date];

NSCalendar *gregorian = [[NSCalendar  alloc]initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *dateComponents = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:now];

[self.timerLabel setText:[NSString stringWithFormat:@"%@ %@ %@", [dateComponents hour], [dateComponents minute], [dateComponents second]]];

当我在self.timerLabel所在的行上运行应用程序崩溃时。

这里有什么问题?

3 个答案:

答案 0 :(得分:1)

当我运行代码时,它在这里工作正常。

代码中的以下行是什么?你确定它在你粘贴的代码的第三行崩溃了吗?也许您粘贴的代码与xcode中的代码不同。

编辑:这是因为您在字符串中使用了属于UTF-8字符串的%@。 [dateComponents hour]等返回NSInteger,所以你应该使用%d代替。

答案 1 :(得分:0)

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]]; 

NSInteger hour= [components hour];   
NSInteger minute = [components minute];
NSInteger second = [components second]; 

答案 2 :(得分:0)

刚做

    NSDate *datenow = [NSDate date];

您将拥有当前日期和时间,要生成日期的字符串表示,您应该使用NSDateFormatter的实例。

相关问题