How to convert a date given as “20110912T220000”(NSString) to NSDate

天大地大妈咪最大 提交于 2019-12-23 22:34:34

问题


I am getting start and end dates for my calendar event(while parsing a .ics file) in "20110912T220000" format. How can I convert this to a NSDate to add to add as event(EKEvent)'s startDate property.

If anyone knows please help me soon.


回答1:


You should use NSDateFormatter for this.

See Data Formatting Guide (the Date & Time Programming Guide may also be interesting)

This is also detailed in this Technical Note in Apple's Q&As. Note that for such situations, you should use the special "en_US_POSIX" locale as explained in this technical note.

NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
[df setDateFormat:@"yyyyMMdd'T'HHmmss"];
NSDate* parsedDate = [df dateFromString:...];



回答2:


NSString *dateString = @"20110912T220000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];  
formatter.locale = locale;
formatter.dateFormat = @"yyyyMMdd'T'HHmmss";
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date: %@", date);

NSLog() output: date: 2011-09-13 02:00:00 +0000

Note, NSLog outputs the data in you local timezone.
Note the single quotes around the 'T' in the date format.

Here is a link to UTS: date/time format characters



来源:https://stackoverflow.com/questions/7554434/how-to-convert-a-date-given-as-20110912t220000nsstring-to-nsdate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!