views:

393

answers:

1

In the docs, Apple gives an example on how to add some hours and minutes to an existing date:

NSDate *today = [NSDate date];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setHour:1];
[offsetComponents setMinutes:30];
NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:comps toDate:today options:0];

But now, I have date which is printed out in 12h format with AM / PM (unicode standard format specifier is "a").

So I have an date object which is set to 8:00 'o clock, and now I want to switch that to PM or 20:00 'o clock. Hard to explain. NSDateComponents doesn't have a component for that.

The docs say that all these NSDateComponents things like hour, minute, day, etc. are in context with a calendar object. Makes sense. But I haven't found anything in NSCalender which would say "this is 12h format" or "this is 24h format".

So actually, what happens when I change the hour period? Isn't that actually just simple math to say "lets take 12 hours off, or lets add 12 hours"? Any idea?

+3  A: 

NSDate is just a value for a moment in time. How you display it, whether it has PM or is in the 24 hour format, is in the formatting.

Here are some formatters:

k gives you 24-hour hours
a gives you AM/PM

From here.

Use the info on that page with NSDateFormatter, like this:

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

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

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

NSString *newDateString = [outputFormatter stringFromDate:formatterDate];

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