我想将服务器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分钟.

推荐答案

I don't know what's wrong with your code.
But looks too much unnecessary things are there like you're setting calendar, fetching some elements from string. Here is my small version of UTCToLocal and localToUTC function.
But for that you need to pass string in specific format. Cause I've forcly unwrapped date objects. But you can use some guard conditions to prevent crashing your app.

func localToUTC(dateStr: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "h:mm a"
    dateFormatter.calendar = Calendar.current
    dateFormatter.timeZone = TimeZone.current
    
    if let date = dateFormatter.date(from: dateStr) {
        dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
        dateFormatter.dateFormat = "H:mm:ss"
    
        return dateFormatter.string(from: date)
    }
    return nil
}

func utcToLocal(dateStr: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "H:mm:ss"
    dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
    
    if let date = dateFormatter.date(from: dateStr) {
        dateFormatter.timeZone = TimeZone.current
        dateFormatter.dateFormat = "h:mm a"
    
        return dateFormatter.string(from: date)
    }
    return nil
}

and call these function like below.

print(utcToLocal(dateStr: "13:07:00"))
print(localToUTC(dateStr: "06:40 PM"))

Hope this will help you.
Happy coding!!

Swift相关问答推荐

Swift中可以取消的延迟任务

如何消除SwiftUI中SF符号的填充

带有文本输入自动大小写修饰符的SwiftUI Textfield问题

SwiftUI map 旋转

无法创建MKAssociateRegion对象

有没有办法让文本字段以不同的 colored颜色 显示而不影响半透明背景?

Swift UI中视图上的值未更新

SwiftUI .task 视图修改器:运行在哪个线程中?

为什么即使 `C` 是一个不是 `Sendable` 的类,Task` 也能工作?

TabView 无法在屏幕上正确显示

从 actor 的 init 方法调用方法

如何在不将变量转换为字符串的情况下判断变量在 Swift 中是否为 Optional(nil)?

为什么 SwiftUI 不在工具栏菜单中反映 @State 属性值?

`let case(value)` 和 `case(let value)` 之间的区别 (Swift)

Vapor - 流利的,将对象保存到 PostgreSQL

macOS 守护进程应该由Command Line ToolXcode 模板制作吗?

如何删除桥头而不出错?

如何在 iOS Swift 中进行多线程、并发或并行?

swift 3 错误:参数标签 '(_:)' 不匹配任何可用的重载

Swift 中的 CommonHMAC