Search code examples
parsingnulltimezonensdateformattervcalendar

Vcal Date Parsing issue


I am having the following string as input :

BEGIN:VCALENDAR
VERSION:2.0
BEGIN:VEVENT
SUMMARY;CHARSET=utf-8:hello 
LOCATION;CHARSET=utf-8:loc 
DTSTART:20120704T053000Z
DTEND:20120704T073000Z
END:VEVENT
END:VCALENDAR

The problem I'm facing is with the date part I'm using :

    NSRange end = [Result rangeOfString:@"T"];

            NSString *DT=[NSString stringWithFormat:@"%@%@",[Result substringToIndex:end.location],[Result substringFromIndex:end.location+1]];

            NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
            [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
            [formatter setDateFormat:@"yyyyMMddHHmmssZ"];

            NSDate *dt=[formatter dateFromString:DT];   

            myEvent.startDate=dt;
            [formatter release];

dt returns here is NULL , what am I doing wrong?

Updated Code: I updated the code as follows , now am able to get date but needed to ask, do i need to set locale or timezone ??

        [NSTimeZone resetSystemTimeZone]; 
        NSLocale *enUSPOSIXLocale;
        NSDateFormatter *sRFC3339DateFormatter = [[NSDateFormatter alloc] init];     

        if( [Result characterAtIndex:[Result length]-2] == 'Z')
        {   
            NSLog(@"in 1");
            [sRFC3339DateFormatter setDateFormat:@"yyyyMMdd'T'HHmmss"];
         }
        else 
        {
            NSLog(@"in 2");
            [sRFC3339DateFormatter setDateFormat:@"yyyyMMdd'T'HHmmssZ"];
        }

        NSDate *date = [sRFC3339DateFormatter dateFromString:[Result substringToIndex:[Result length]-2]];

        myEvent.startDate=date;

Solution

  • Look at your format:

    [formatter setDateFormat:@"yyyyMMddHHmmssZ"];
    

    Now look at an example string:

    20120704T073000Z
    

    You're missing the T. I don't know whether it needs escaping, so you might want either of these:

    [formatter setDateFormat:@"yyyyMMddTHHmmssZ"];
    [formatter setDateFormat:@"yyyyMMdd'T'HHmmssZ"];
    

    Note that the Z at the end means "UTC" - I don't know whether iOS will automatically take that into account or not, but it at least means that setting the time zone to the default time zone is misleading. I'd set it to UTC or not at all.