获得领先零的时间

OhD*_*Doh 0 objective-c ios

是我之前关于在objective-c中使用date的问题.如何使用前导零获得小时,分钟和秒?

sch*_*sch 6

现在您已经将小时,分钟和秒作为字符串进行了精确处理,以下是如何获取它们:

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];
Run Code Online (Sandbox Code Playgroud)

关键是"%02d"在格式化时使用,以保证你得到两位数.