随时获取UTC时间并处理夏令时

时间:2016-08-29 09:46:28

标签: ios objective-c iphone nsdateformatter ios9.3

我编写了一个函数来获取与时间字符串相对应的UTC时间字符串作为参数传递给函数。

+(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;
}

它适用于印度孟买时区。但是,如果我将时区更改为伦敦,它会在我传递函数参数的同时返回我。目前在伦敦是UTC + 1。 NSDateFormatter会处理夏令时吗?

1 个答案:

答案 0 :(得分:1)

您可以使用下面显示的 NSTimeZone 方法进行夏令时:请参阅NSTimeZone Class Reference

  1. isDaylightSavingTimeForDate: //会告诉您此日期是否存在日间照明
  2. daylightSavingTimeOffset //将告诉您夏令时的偏移量
  3. 使用下面的代码正确返回带偏移的日光保存

    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
    
相关问题