小编典典

Swift 3.0:将服务器UTC时间转换为本地时间,反之亦然

swift

我想将服务器UTC时间转换为本地时间,反之亦然。这是我的代码。

var isTimeFromServer = true
var time:String!
var period:String!
let timeString = "6:59 AM" //Current UTC time

if isTimeFromServer {

    let index = timeString.index(timeString.startIndex, offsetBy: 5)
    let twelve = timeString.substring(to: index)

    var dateString:String!

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H:mm"
    let date12 = dateFormatter.date(from: twelve)!

    dateFormatter.dateFormat = "h:mm a"
    let date22 = dateFormatter.string(from: date12)

    //print(date22)
    dateString = date22
    //print("dateString=\(dateString)")

    time = dateString.components(separatedBy: " ")[0]
    period = dateString.components(separatedBy: " ")[1]

}
else {
    time = timeString.components(separatedBy: " ")[0]
    period = timeString.components(separatedBy: " ")[1]
}

var hour = Int(time.components(separatedBy: ":")[0])

hour = period == "AM" ? hour : hour! + 12
let minute = Int(time.components(separatedBy: ":")[1])
let calender = NSCalendar.current
var datecomponent = DateComponents()
datecomponent.calendar = calender
datecomponent.hour = hour
datecomponent.minute = minute

if !isTimeFromServer {
    // local to UTC
    datecomponent.timeZone = TimeZone.current
}
else {
    datecomponent.timeZone = TimeZone(abbreviation: "UTC")
}

let date = datecomponent.date
let dateFormatter = DateFormatter()

if !isTimeFromServer {
    dateFormatter.dateFormat = "H:mm"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    dateFormatter.string(from: date!)
}
else {
    //UTC to local
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.string(from: date!)
}

我知道当地时间

o / p:“下午12:52”

但是实际的本地时间和输出时间相差23分钟。


阅读 727

收藏
2020-07-07

共1个答案

小编典典

我不知道您的代码有什么问题。
但是看起来有太多不必要的事情,就像您要设置日历,从字符串中获取某些元素一样。这是我的UTCToLocal和localToUTC函数的小版本。
但是为此,您需要以特定格式传递字符串。原因我已强制打开日期对象。但是您可以使用一些保护条件来防止应用程序崩溃。

func localToUTC(date:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.calendar = NSCalendar.current
    dateFormatter.timeZone = TimeZone.current

    let dt = dateFormatter.date(from: date)
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    dateFormatter.dateFormat = "H:mm:ss"

    return dateFormatter.string(from: dt!)
}

func UTCToLocal(date:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H:mm:ss"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

    let dt = dateFormatter.date(from: date)
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.dateFormat = "h:mm a"

    return dateFormatter.string(from: dt!)
}

然后像下面这样调用这些函数。

print(UTCToLocal(date: "13:07:00"))
print(localToUTC(date: "06:40 PM"))

希望这会帮助你。
编码愉快!!

2020-07-07