Getting the current time

I am trying to get the current minutes and seconds. Here is the code I'm using

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]]];

When I run the application crash in the line where self.timerLabel is located.

What is wrong here?

+1
source share
3 answers
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]]; 

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

When I run the code, it works fine here.

what is the next line in the code? Are you sure it will work on the third line of code that you inserted? maybe the code you pasted does not match your xcode code.

Edit: this is because you are using% @ in your line, which belongs to the UTF-8 line. [dateComponents hour] etc. return NSInteger, so you should use% d instead.

+1
source

    NSDate *datenow = [NSDate date];

you will have the current date and time, to generate string representations of the date, you must use an instance of NSDateFormatter.

0
source

All Articles