fuzzygoat
fuzzygoat

Reputation: 26223

NSDateComponents specifying AM/PM?

I am building up a date using NSDateComponents from the following string:

"2014-05-17 02:39:00 PM +0000"

When I set all the components and return an NSDate I am getting (see method below):

"2014-05-17 02:39:00 AM +0000"

My question is, is there a way to specify the AM/PM to NSDateComponent, or do I just have to add 12 to my hour if the source date is PM?

- (NSDate *)dateFromYear:(int)year month:(int)month day:(int)day hour:(int)hour minute:(int)minute {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    [components setHour:hour];
    [components setMinute:minute];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateFromComponents:components];
}

Upvotes: 1

Views: 3232

Answers (1)

Nirav Bhatt
Nirav Bhatt

Reputation: 6969

Apparently, NSDateComponents doesn't seem to specify this. Apple's own docs on it says this:

Important: An NSDateComponents object is meaningless in itself; you need to know what calendar it is interpreted against, and you need to know whether the values are absolute values of the units, or quantities of the units.

Apart from your 12 hours logic, you can alternately use NSDate class dateWithNaturalLanguageString that uses AM/PM and make use it somehow for your purpose.

Upvotes: 1

Related Questions