开发者

Convert NSString date to NSDate

开发者 https://www.devze.com 2023-02-20 14:10 出处:网络
Is there an effective way of converting from this type of NSString data to an NSDate: 开发者_StackOverflow中文版

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:"];
0

精彩评论

暂无评论...
验证码 换一张
取 消