Reputation: 183
I really need help. The code result is 2:0:0
while the format is set to hh:mm:ss
. I want the result to be 2:00:00
(adding 0
in front of 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 this?
Upvotes: 4
Views: 1169
Reputation: 27073
Log using the %02ld
specifier, for example:
NSLog(@"%ld:%02ld:%02ld",[differenceComponents hour],[differenceComponents minute],[differenceComponents second]);
Output:
2:00:00
Additionally create NSStrings
like this:
NSString *theString = [NSString stringWithFormat:@"%ld:%02ld:%02ld",[differenceComponents hour],[differenceComponents minute],[differenceComponents second]];
NSLog(@"%@",theString);
Upvotes: 6
Reputation: 2506
The Problem is: 00-00 is 0. I used to have the 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 it like this in your NSLog:
NSLog(@"%@:%@:%@",[self formatIntToString:[differenceComponents hour]],[self formatIntToString:[differenceComponents minute]],[self formatIntToString:[differenceComponents second]]);
Upvotes: 0