NSLog minutes and seconds NSDateComponents - how to display leading zeros?

I really need some help. The result of the code is 2:0:0 , and the format is hh:mm:ss . I want the result to be 2:00:00 (adding 0 before the minutes and seconds when they are under 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]); 

How to do it?

+4
source share
2 answers

Log using the %02ld , for example:

 NSLog(@"%ld:%02ld:%02ld",[differenceComponents hour],[differenceComponents minute],[differenceComponents second]); 

Output:

 2:00:00 

Alternatively, create NSStrings as follows:

 NSString *theString = [NSString stringWithFormat:@"%ld:%02ld:%02ld",[differenceComponents hour],[differenceComponents minute],[differenceComponents second]]; NSLog(@"%@",theString); 
+6
source

Problem: 00-00 is 0. I used to have a problem and solved it like this:

 -(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; }} 

Use this in NSLog:

 NSLog(@"%@:%@:%@",[self formatIntToString:[differenceComponents hour]],[self formatIntToString:[differenceComponents minute]],[self formatIntToString:[differenceComponents second]]); 
0
source

All Articles