objective-c - 获得前导零的时间

标签 objective-c ios

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/

相关文章:

ios - 如果设备关闭,尝试在 IOS 应用程序中检索以前配对的蓝牙设备将不会响应失败

iphone - 我怎样才能在iPhone中将一个类的值赋予另一个类?

iphone - UISwipeGestureRecognizer 手势起点

ios - 解析 - Swift 中的 NSNull null 模拟

ios - CGAffineTransformMakeTranslation 除了一个 subview

ios - 从给定的字符串中仅检索正整数

ios - 在 Swift 中将图像合并为 PDF

iphone - 我如何使用 Core Animation 在我自己的类上随时间插入属性值?

ios - Xcode9无线调试上不了大学网

iphone - 在 iOS 上加载压缩图像的最快方法是什么?