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?
You can use NSTimeZone methods as shown below for daylight saving: See NSTimeZone Class Reference
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