Here是我之前关于在 Objective-C 中使用日期的问题。如何获取带前导零的小时、分钟和秒?
最佳答案
既然您已经明确需要将小时、分钟和秒作为字符串,下面是获取它们的方法:
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];
关键是在格式化的时候使用"%02d"
,保证得到两位数。
关于objective-c - 获得前导零的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9318583/