iosobjective-ciphonensdateformatterios9.3

Getting UTC time for any time and handling daylight saving as well


I have written a function to get UTC time string corresponding to any time string passed as an argument to function.

+(NSString *)getUTCTime:(NSString *)selectedTime
{
    NSString *strFormat;
    if ([self is24HourFormat:selectedTime]){
        strFormat = @"HH:mm";
    }
    else{
        strFormat = @"hh:mm a";
    }
    NSLocale *baseLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

    NSDateFormatter *dateFormatterlocal = [[NSDateFormatter alloc] init];
    [dateFormatterlocal setTimeZone:[NSTimeZone systemTimeZone]];
    dateFormatterlocal.locale = baseLocale;
    [dateFormatterlocal setDateFormat:strFormat];

    NSDate *selectedDate = [dateFormatterlocal dateFromString:selectedTime];

    NSDateFormatter *dateFormatterUTC = [[NSDateFormatter alloc] init];
    [dateFormatterUTC setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
    dateFormatterUTC.locale = baseLocale;
    [dateFormatterUTC setDateFormat:strFormat];


    NSString *utcTimeString = [dateFormatterUTC stringFromDate:selectedDate];
    return utcTimeString;
}

It working fine for Mumbai, India time zone. But if i change the timezone to London, its returning me the same time that I'm passing in function argument. Currently it is UTC+1 in London. Does NSDateFormatter handle daylight saving?


Solution

  • You can use NSTimeZone methods as shown below for daylight saving: See NSTimeZone Class Reference

    1. isDaylightSavingTimeForDate:// will tell you if day light saving exist for this date
    2. daylightSavingTimeOffset // will tell you how much offset is the time for daylight saving

    Use below code it returns properly day light saving with offset

    var timeZone:NSTimeZone = NSTimeZone(name:"Europe/London")!
    print(timeZone.daylightSavingTime) //this will return true if day light saving present
    print(timeZone.daylightSavingTimeOffset/(60*60))//this will give you number of hours by which the day light saving offset should be
    print("timezone: \(timeZone)")//will give you detail about timezone