2

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.

2 Answers2

4

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:...];
Gabe
  • 82,547
  • 12
  • 135
  • 231
AliSoftware
  • 32,535
  • 6
  • 79
  • 76
0
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

zaph
  • 110,296
  • 20
  • 185
  • 221
  • Err there's something wrong with your `formatter = @"..."`: you probably forgot the `dateFormat` property here ;) – AliSoftware Sep 26 '11 at 12:39