2010-04-04 51 views
2

如何以hh:mm格式獲取當前時間?我需要能夠分辨上午和下午之間的時間,並比較當前時間和第二次。我相信這是一個愚蠢的功能,但我似乎無法弄清楚。在Objective-c中檢查時間?

回答

3

當前日期的日期比較:

NSDate * now = [NSDate date]; 
NSDate * mile = [[NSDate alloc] initWithString:@"2001-03-24 10:45:32 +0600"]; 
NSComparisonResult result = [now compare:mile]; 

NSLog(@"%@", now); 
NSLog(@"%@", mile); 

switch (result) 
{ 
    case NSOrderedAscending: NSLog(@"%@ is in future from %@", mile, now); break; 
    case NSOrderedDescending: NSLog(@"%@ is in past from %@", mile, now); break; 
    case NSOrderedSame: NSLog(@"%@ is the same as %@", mile, now); break; 
    default: NSLog(@"erorr dates %@, %@", mile, now); break; 
} 

[mile release]; 

日期格式存在NSDateFormatter。您可以在數據從鏈接格式指南,例如更Date and Time programming guide for cocoaDate formatters

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
[inputFormatter setDateFormat:@"yyyy-MM-dd 'at' HH:mm"]; 

NSDate *formatterDate = [inputFormatter dateFromString:@"1999-07-11 at 10:30"]; 

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; 
[outputFormatter setDateFormat:@"HH:mm 'on' EEEE MMMM d"]; 

NSString *newDateString = [outputFormatter stringFromDate:formatterDate]; 

NSLog(@"newDateString %@", newDateString); 
// For US English, the output is: 
// newDateString 10:30 on Sunday July 11 
+0

我曾經佔領了接下來的幾天,但我會檢查並送還給你。順便說一句,我不想​​要日期代碼。 – Moshe 2010-04-04 23:05:11

+0

'NSDate'類表示Cocoa中的日期和時間,我剛剛複製了一些我有的例子,你應該能夠弄清楚如何更新格式化字符串以獲得時間...... – stefanB 2010-04-04 23:07:28