在时区之间转换日期 swift

Converting date between timezones swift

我在 GMT 中的在线服务器数据库中存储了一个日期。我加载日期并使用以下代码将其转换为用户的时区:

 if let messagedate = oneitem["timestamp"] as? String {
     let dateFormatter = NSDateFormatter()
     dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
     let date = dateFormatter.dateFromString(messagedate)
     let source_timezone = NSTimeZone(abbreviation: "GMT")
     let local_timezone = NSTimeZone.systemTimeZone()
     let source_EDT_offset = source_timezone?.secondsFromGMTForDate(date!)
     let destination_EDT_offset = local_timezone.secondsFromGMTForDate(date!)
     let time_interval : NSTimeInterval = Double(destination_EDT_offset - source_EDT_offset!)


     let final_date = NSDate(timeInterval: time_interval, sinceDate: date!)
     curr_item.date = final_date
 }

现在我需要将日期转换回 GMT 以便与服务器通信,但是我不确定如何将其转换回 GMT

由于 NSDate 始终处于 GMT/UTC 时区仅在向用户显示时区或从用户处获取时区才变得相关。只要在内部始终假设它是 UTC,根据需要为用户转换它(通过在 NSDateFormatter 上设置),您就不必再担心这个问题了。

您不能再次使用不同时区的数据格式化程序并进行转换吗?比如

dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT")
let gmtDate = dateFormatter.dateFromString(string: "your old date as string here")

我建议

  • 您在 dateFormatter 上设置了 GMT 时区以直接返回 UTC 的 NSDate(只有 UTC 的 NSDates 是一个好习惯)
  • 当您需要显示它时,您可以使用另一个设置了本地时区的 NSDateFormatter(默认设置)
  • 当你需要向你的服务器发送一个日期时,你再次使用dateFormatter生成一个字符串

效率提高约 50 倍

extension Date {
    func convertToLocalTime(fromTimeZone timeZoneAbbreviation: String) -> Date? {
        if let timeZone = TimeZone(abbreviation: timeZoneAbbreviation) {
            let targetOffset = TimeInterval(timeZone.secondsFromGMT(for: self))
            let localOffeset = TimeInterval(TimeZone.autoupdatingCurrent.secondsFromGMT(for: self))

            return self.addingTimeInterval(targetOffset - localOffeset)
        }

        return nil
    }
}

更简单的版本:

extension Date {
    func convertToTimeZone(initTimeZone: TimeZone, timeZone: TimeZone) -> Date {
         let delta = TimeInterval(timeZone.secondsFromGMT(for: self) - initTimeZone.secondsFromGMT(for: self))
         return addingTimeInterval(delta)
    }
}

基于,但更正了表达式中免赔额的顺序。

extension Date {    
    func convert(from initTimeZone: TimeZone, to targetTimeZone: TimeZone) -> Date {
        let delta = TimeInterval(initTimeZone.secondsFromGMT() - targetTimeZone.secondsFromGMT())
        return addingTimeInterval(delta)
    }    
}

在撰写本文时,大多数答案都包含 DST 切换时间附近的边缘案例错误(请参阅下面关于其他答案的注释)。如果您只想将日期 stringno time offset 转换为特定时区的 Date 是最好的,但是为了那些有“如何在时区之间转换Date”问题的人的利益,有两种情况:

案例 1:

Date 转换为另一个时区,同时保留初始时区的日期和时间。

例如GMT 到 EST:2020-03-08T10:00:00Z2020-03-08T10:00:00-04:00

案例 2:

Date 转换为其他时区的日期和时间,同时保留初始时区。

例如对于 EST 到 GMT:2020-03-08T06:00:00-04:002020-03-08T10:00:00-04:00(因为初始 Date 是 GMT 上午 10 点)

这两种情况实际上是相同的(示例开始和结束 Dates 是相同的),只是它们的措辞不同以交换哪个时区是“初始”,哪个是“目标” .因此,如果您交换时区,下面的两个解决方案是等效的,因此您可以选择概念上更适合您的用例的解决方案。

extension Calendar {

    // case 1
    func dateBySetting(timeZone: TimeZone, of date: Date) -> Date? {
        var components = dateComponents(in: self.timeZone, from: date)
        components.timeZone = timeZone
        return self.date(from: components)
    }

    // case 2
    func dateBySettingTimeFrom(timeZone: TimeZone, of date: Date) -> Date? {
        var components = dateComponents(in: timeZone, from: date)
        components.timeZone = self.timeZone
        return self.date(from: components)
    }
}

// example values
let initTz = TimeZone(abbreviation: "GMT")!
let targetTz = TimeZone(abbreviation: "EST")!
let initDate = Calendar.current.date(from: .init(timeZone: initTz, year: 2020, month: 3, day: 8, hour: 4))!

// usage
var calendar = Calendar.current
calendar.timeZone = initTz
let case1TargetDate = calendar.dateBySetting(timeZone: targetTz, of: initDate)!
let case2TargetDate = calendar.dateBySettingTimeFrom(timeZone: targetTz, of: initDate)!

// print results
let formatter = ISO8601DateFormatter()
formatter.timeZone = targetTz // case 1 is concerned with what the `Date` looks like in the target time zone
print(formatter.string(from: case1TargetDate)) // 2020-03-08T04:00:00-04:00
// for case 2, find the initial `Date`'s time in the target time zone
print(formatter.string(from: initDate)) // 2020-03-07T23:00:00-05:00 (the target date should have this same time)
formatter.timeZone = initTz // case 2 is concerned with what the `Date` looks like in the initial time zone
print(formatter.string(from: case2TargetDate)) // 2020-03-07T23:00:00Z

关于其他答案的注释

在撰写本文时,大多数其他答案都假设了上述两种情况之一,但更重要的是,它们都有一个错误——它们试图计算时区之间的时差,其中时差的符号决定了案例:

案例 1:

initialTz.secondsFromGMT(for: initialDate) - targetTz.secondsFromGMT(for: initialDate)

案例二:

targetTz.secondsFromGMT(for: initialDate) - initialTz.secondsFromGMT(for: initialDate)

secondsFromGMT 采用您想知道其偏移量的 Date,因此在这两种情况下,目标偏移量实际上应该是 targetTz.secondsFromGMT(for: targetDate),这是一个 catch-22,因为我们还不知道目标日期。然而,在大多数情况下 Date 很接近,就像它们在这里一样,targetTz.secondsFromGMT(for: initialDate)targetTz.secondsFromGMT(for: targetDate) 是相等的 - 只有当它们不同,这发生在目标时区中两个 Date 之间的时间偏移发生变化时,例如对于夏令时。这是每个案例的错误示例:

extension Date {

    // case 1 (bugged)
    func converting(from initTz: TimeZone, to targetTz: TimeZone) -> Date {
        return self + Double(initTz.secondsFromGMT(for: self) - targetTz.secondsFromGMT(for: self))
    }

    // case 2 (bugged)
    func convertingTime(from initTz: TimeZone, to targetTz: TimeZone) -> Date {
        return self + Double(targetTz.secondsFromGMT(for: self) - initTz.secondsFromGMT(for: self))
    }
}

let formatter = ISO8601DateFormatter()

//  case 1
do {
    // example values
    let initTz = TimeZone(abbreviation: "GMT")!
    let targetTz = TimeZone(abbreviation: "EST")!
    let initDate = Calendar.current.date(from: .init(timeZone: initTz, year: 2020, month: 3, day: 8, hour: 4))!

    // usage
    let targetDate = initDate.converting(from: initTz, to: targetTz)

    // print results
    formatter.timeZone = targetTz // case 1 is concerned with what the `Date` looks like in the target time zone
    print(formatter.string(from: targetDate)) // 2020-03-08T05:00:00-04:00 (should be 4am)
}

//  case 2
do {
    // example values
    let initTz = TimeZone(abbreviation: "EST")!
    let targetTz = TimeZone(abbreviation: "GMT")!
    let initDate = Calendar.current.date(from: .init(timeZone: initTz, year: 2020, month: 3, day: 8, hour: 1))!

    // usage
    let targetDate = initDate.convertingTime(from: initTz, to: targetTz)

    // print results
    formatter.timeZone = targetTz // for case 2, find the initial `Date`'s time in the target time zone
    print(formatter.string(from: initDate)) // 2020-03-08T06:00:00Z (the target date should have this same time)
    formatter.timeZone = initTz // case 2 is concerned with what the `Date` looks like in the initial time zone
    print(formatter.string(from: targetDate)) // 2020-03-08T07:00:00-04:00 (should be 6am)
}

如果将示例日期向前或向后调整几个小时,则不会出现此错误。日历计算很复杂,尝试自己动手几乎总是会导致错误的边缘情况。由于时区是一个日历单位,为避免错误,您应该使用现有的 Calendar 界面,如我最初的示例。

所以这是 enhanced with 夏令时:

func convert(from initTimeZone: TimeZone, to targetTimeZone: TimeZone) -> Date {
    let delta = TimeInterval(targetTimeZone.secondsFromGMT(for: self) - initTimeZone.secondsFromGMT(for: self))
    return addingTimeInterval(delta)
}

详情

  • Xcode 11.4.1 (11E503a), Swift 5.2

解决方案 1

Based on answer

import Foundation
extension Date {
    func to(timeZone outputTimeZone: TimeZone, from inputTimeZone: TimeZone) -> Date {
         let delta = TimeInterval(outputTimeZone.secondsFromGMT(for: self) - inputTimeZone.secondsFromGMT(for: self))
         return addingTimeInterval(delta)
    }
}

解决方案 1 的用法

let utcTimeZone = TimeZone(abbreviation: "UTC")!
let dateString = "2020-06-03T01:43:44.888Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from: dateString)

print(date)
print(date?.to(timeZone: .autoupdatingCurrent, from: utcTimeZone))
print(date?.to(timeZone: .current, from: utcTimeZone))
print(date?.to(timeZone: TimeZone(abbreviation: "PDT")!, from: utcTimeZone))

解决方案 2

Do not forget to paste the Solution 1 code here

extension DateFormatter {
    func date(from string: String, timeZoneInString: TimeZone, outputTimeZone: TimeZone = .autoupdatingCurrent) -> Date? {
        date(from: string)?.to(timeZone: outputTimeZone, from: timeZoneInString)
    }
}

方案2的用法

let utcTimeZone = TimeZone(abbreviation: "UTC")!
let pdtTimeZone = TimeZone(abbreviation: "PDT")!
let dateString = "2020-06-03T01:43:44.888Z"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

print(dateFormatter.date(from: dateString))
print(dateFormatter.date(from: dateString, timeZoneInString: utcTimeZone))
print(dateFormatter.date(from: dateString, timeZoneInString: utcTimeZone, outputTimeZone: pdtTimeZone))

完全正确,使用 secondsFromGMT(for: date) 无法有效处理夏令时,但他们的扩展示例是针对 Calendar 的。下面的扩展是针对 date 的,它达到了同样的目的:

extension Date {

    func convert(from timeZone: TimeZone, to destinationTimeZone: TimeZone) -> Date {
        let calendar = Calendar.current
        var components = calendar.dateComponents(in: timeZone, from: self)
        components.timeZone = destinationTimeZone
        return calendar.date(from: components)!
    }
}