Convert NSString date to NSDate
Is there an effective way of converting from this type of NSString data to an NSDate:
开发者_StackOverflow中文版2011-05-07+02:00
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.
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];
Use:
[ NSDate dateWithString: myStr ];
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
See dateWithString:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
Regards Friedrich
As ssteinberg said, and the format is as following.
// 2011-05-07+02:00
[dateFormatter setDateFormat:@"yyyy-MM-dd+hh:mm:"];
精彩评论