Reputation: 433
Here is my previous question about using date in objective-c. How to get hours, minutes and seconds with leading zeroes ?
Upvotes: 0
Views: 1016
Reputation: 27506
Now that you precised that you want hours, minutes and seconds as strings, here is how to get them:
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger hour= [components hour];
NSInteger minute = [components minute];
NSInteger second = [components second];
NSString *hourString = [NSString stringWithFormat:@"%02d", hour];
NSString *minuteString = [NSString stringWithFormat:@"%02d", minute];
NSString *secondString = [NSString stringWithFormat:@"%02d", second];
The key is to use "%02d"
when formatting, to guarantee that you get two digits.
Upvotes: 6
Reputation: 385540
I think that you want to format your “date” into a string, and you want leading zeroes in the string.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm:ss"];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
Upvotes: 2