简体   繁体   English

如何获取特定时区的当前时间?

[英]How to get the current time in a specific timezone?

I am currently working on an app where I have the necessity to get the current date and time in the Europe/Rome timezone.我目前正在开发一个应用程序,我需要在该应用程序中获取欧洲/罗马时区的当前日期和时间。 I have created the following method to do so:为此,我创建了以下方法:

static func getItalianDate() -> Date {
    let timezone = TimeZone(identifier: "Europe/Rome")!
    let seconds = TimeInterval(timezone.secondsFromGMT(for: Date()))
    let date = Date(timeInterval: seconds, since: Date())

    return date
}

This however won't return the correct value in case the user manipulates the date and timezone from the settings General -> Date and Time and I can't figure out how to get the correct answer.但是,如果用户从设置“常规”->“日期和时间”操纵日期和时区,并且我无法弄清楚如何获得正确答案,这将不会返回正确的值。 The format I need is something like: "yyyy-MM-dd HH:mm:ss".我需要的格式类似于:“yyyy-MM-dd HH:mm:ss”。

Any suggestion?有什么建议吗?

EDIT编辑

I found this question - still unanswered - with the same problem I am facing here.我发现这个问题- 仍然没有答案 - 与我在这里面临的问题相同。 Is using a server the only option available?使用服务器是唯一可用的选项吗?

let dateFormatter = {
    var df = DateFormatter()
    df.timeZone = Calendar.current.timeZone
    df.dateFormat = ”yyyy-MM-dd HH:mm:ss”
    return df
}()

let timestamp = dateFormatter.string(from: date)
// display your timestamp

In case you your app needs to refresh its view upon timezone changes (hence recalculate the timestamp to display), either react to NSSystemTimeZoneDidChange notification in case is UIKit based or use the SwiftUI environment timeZone global variable in case its view is SwiftUI based.如果您的应用程序需要在时区更改时刷新其视图(因此重新计算要显示的时间戳),则在基于 UIKit 的情况下响应 NSSystemTimeZoneDidChange 通知,或者在其视图基于 SwiftUI 的情况下使用 SwiftUI 环境时区全局变量。

import Foundation

// 1. Choose a date
let today = Date()

// 2. Pick the date components
let hours   = (Calendar.current.component(.hour, from: today))
let minutes = (Calendar.current.component(.minute, from: today))
let seconds = (Calendar.current.component(.second, from: today))

// 3. Show the time
print("\(hours):\(minutes):\(seconds)") 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM