问题
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