TheLearner
TheLearner

Reputation: 19507

Convert NSString date to NSDate

Is there an effective way of converting from this type of NSString data to an NSDate:

2011-05-07+02:00

Upvotes: 0

Views: 1599

Answers (5)

Thomas Desert
Thomas Desert

Reputation: 1346

You should use the NSDateFromatter class for this. Set the format of your date, then use

- (NSDate *)dateFromString:(NSString *)string

method. See NSDateFormatter reference for details.

Upvotes: 1

AechoLiu
AechoLiu

Reputation: 18378

As ssteinberg said, and the format is as following.

// 2011-05-07+02:00
[dateFormatter setDateFormat:@"yyyy-MM-dd+hh:mm:"];

Upvotes: 0

unexpectedvalue
unexpectedvalue

Reputation: 6139

Much better alternative is using NSDateFormatter. You can specify string format, locale, timezone.

dateFormatter = [[NSDateFormatter alloc] init];

NSLocale *en_US = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:en_US];
[en_US release];

[dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-60*60*7]];
NSDate *date = [dateFormatter dateFromString:dateString];

[dateFormatter release];

Upvotes: 1

Related Questions