2012-08-30 63 views
4

我真的需要幫助。代碼結果爲2:0:0,格式設置爲hh:mm:ss。我希望結果爲2:00:00(在10之下時,在分鐘和秒前增加0)。NSLog分鐘和NSDateComponents秒 - 如何顯示前導零?

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]); 

如何做到這一點?

回答

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); 
+0

該死的我太sooo困惑..謝謝你!! :* – Stackie

+0

在這種情況下,您可能希望詳細說明'%02ld'的具體含義。 –

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]]); 
+0

是的,我讓你的想法,但感謝!第一個答案更容易 – Stackie