Search code examples
iosobjective-cxcodecalendarnsdate

Converting calendar date to the correct date


I am working on an application that creates alerts with calendar. I can correctly set alarms on correct dates. For example, I set an alarm for 4th of May 2017 1 PM.

When, I try to get the calendar event it returns me some other date in UTC.

enter image description here

As you can see, it returns me 10 AM on same day with UTC. I am wondering how can I get the exact date when I try to get it from calendar.


Solution

  • You just need to convert UTC to your local timezone.

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    NSDate *date1 = [dateFormatter dateFromString:@"2017-05-04 10:00:00"];
    
    // change to a readable time format and change to local time zone
    [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm a"];
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    NSString *strCurrentLocalTimezoneDate = [dateFormatter stringFromDate:date1];