views:

165

answers:

1

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.

+2  A: 

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
stefanB
I'm ocupied for the next few days but I will check this and get back to you. I do not want the date code, by the way, just the time.
Moshe
the `NSDate` class represents dates and times in Cocoa, I've just copy couple of examples that I have, you should be able to figure out how to update the format string to get just the time ...
stefanB