检查Objective-c中的时间?

时间:2010-04-04 22:36:08

标签: ios objective-c datetime time

如何以hh:mm格式获取当前时间?我需要能够在AM和PM之间进行分析,并在当前时间和第二时间之间进行比较。我确定这是一个愚蠢的功能,但我似乎无法弄明白。

1 个答案:

答案 0 :(得分: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