我真的需要帮助。代码结果为2:0:0
,格式设置为hh:mm:ss
。我希望结果为2:00:00
(在0
下的分钟和秒之前添加10
。
NSDateFormatter *test = [[NSDateFormatter alloc] init];
[test setDateFormat:@"HH:mm:ss"];
NSDate *date1 = [test dateFromString:@"18:00:00"];
NSDate *date2 = [test dateFromString:@"20:00:00"];
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int uintFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents* differenceComponents = [gregorian components:uintFlags fromDate:date1 toDate:date2 options:0];
NSLog(@"%d:%d:%d",[differenceComponents hour],[differenceComponents minute],[differenceComponents second]);
怎么做?
答案 0 :(得分:6)
使用%02ld
说明符进行记录,例如:
NSLog(@"%ld:%02ld:%02ld",[differenceComponents hour],[differenceComponents minute],[differenceComponents second]);
输出:
2:00:00
另外像这样创建NSStrings
:
NSString *theString = [NSString stringWithFormat:@"%ld:%02ld:%02ld",[differenceComponents hour],[differenceComponents minute],[differenceComponents second]];
NSLog(@"%@",theString);
答案 1 :(得分:0)
问题是:00-00为0。 我曾经遇到过这个问题并且像这样解决了它
-(NSString*)formatIntToString:(int)inInt{
if (inInt <10) {
NSString *theString = [NSString stringWithFormat:@"0%d",inInt];
return theString;
}
else {
NSString *theString = [NSString stringWithFormat:@"%d",inInt];
return theString;
}}
在NSLog中使用它:
NSLog(@"%@:%@:%@",[self formatIntToString:[differenceComponents hour]],[self formatIntToString:[differenceComponents minute]],[self formatIntToString:[differenceComponents second]]);