0

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?

Beltalowda
  • 4,558
  • 2
  • 25
  • 33
Varun Mehta
  • 1,733
  • 3
  • 18
  • 39

1 Answers1

1

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
Omer Malik
  • 409
  • 7
  • 15
  • For London timezone its returning 0.000 offset. But right now it is UTC+1 in london. – Varun Mehta Aug 29 '16 at 10:15
  • @VarunMehta I have updated the **comment** and tested in on playground it works fine and gives me 1 offset for Europe/London. check above code and all the best. – Omer Malik Aug 29 '16 at 11:05