4

我真的需要帮助。代码结果是2:0:0格式设置为hh:mm:ss. 我希望结果是2:00:000在分钟和秒的前面加上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]);

这该怎么做?

4

2 回答 2

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);
于 2012-08-31T00:42:40.033 回答
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]]);
于 2012-08-31T00:40:28.577 回答