开发者

Checking the time in Objective-c?

how can I get the current time in hh:mm format? I need to be able to tell between AM and PM and compare between the current time and a second time as well. I'm sure it's a silly function but i can't seem to figure it开发者_开发知识库 out.


Current date and comparison of dates:

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

For date formatting there is an NSDateFormatter. You can find more in Date and Time programming guide for cocoa and Date formatters in data formatting guide, example from the link:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜