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

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

我编写了一个函数来获取与作为参数传递给函数的任何时间字符串相对应的 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 是否处理夏令时?

您可以使用如下所示的 NSTimeZone 方法来实现夏令时:参见 NSTimeZone Class Reference

  1. isDaylightSavingTimeForDate:// 会告诉你这个日期是否存在夏令时
  2. daylightSavingTimeOffset // 会告诉你夏令时的偏移量是多少

使用下面的代码 returns 正确的夏令时和偏移

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