简体   繁体   English

如何从 Swift 中的时间服务器获取当前时区的当前日期?

[英]How to get current date from current timezone from a time server in Swift?

I am working on application where i want to get current date as per the users current timezone.我正在开发我想根据用户当前时区获取当前日期的应用程序。 even after user changes date from their device setting menu.即使在用户从他们的设备设置菜单中更改日期之后。

To get the current timezone i have used获取我使用的当前时区

let timeZone = TimeZone.current
print(timeZone)

for example here i got 'Asia/Kolkata' and current date is 28-july, now if user changes date (Setting->Date&Time-> off set automatically) to 29-july at that time i got output like 'Asia/Kolkata' date 29-july, but actual date is 28-july.例如,我在这里得到“亚洲/加尔各答”,当前日期是 7 月 28 日,现在如果用户将日期(设置-> 日期和时间-> 自动关闭)更改为 7 月 29 日,当时我得到了 output,如“亚洲/加尔各答”日期为 7 月 29 日,但实际日期为 7 月 28 日。 so how can i get current date of this (Asia/Kolkata) timezone.那么我怎样才能获得这个(亚洲/加尔各答)时区的当前日期。

Note: I want to use this because i need current date of particular timezone if user tries to change date from setting then after i need to get exact date from that timezone.注意:我想使用它,因为如果用户尝试从设置更改日期然后我需要从该时区获取确切日期,我需要特定时区的当前日期。

Here is a simple solution:这是一个简单的解决方案:

let timezone = TimeZone.current
let seconds = TimeInterval(timezone.secondsFromGMT(for: Date()))
let date = Date(timeInterval: seconds, since: Date())
print(date)

You could simply use Date() too, but while using it to display it use DateFormatter .您也可以简单地使用Date() ,但是在使用它来显示它时使用DateFormatter Here's an example:这是一个例子:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let formattedDate = dateFormatter.string(from: Date())
print(formattedDate)

If you need to make sure the date is a valid date you can use a timeserver to return the date based on the device IP, of course this will require an internet connection.如果您需要确保日期是有效日期,您可以使用时间服务器根据设备 IP 返回日期,当然这需要互联网连接。

You can create a asynchronous method to return the current date regardless of the user timezone and its timezone as well:您可以创建一个异步方法来返回当前日期,而不考虑用户时区及其时区:


struct Root: Codable {
    let unixtime: Date
    let timezone: String
}

extension URL {
    static let timeIP = URL(string: "http://worldtimeapi.org/api/ip")!
    static func asyncTime(completion: @escaping ((Date?, TimeZone?, Error?)-> Void)) {
        URLSession.shared.dataTask(with: .timeIP) { data, response, error in
            guard let data = data else {
                completion(nil, nil, error)
                return
            }
            do {
                let decoder = JSONDecoder()
                decoder.dateDecodingStrategy = .secondsSince1970
                let root = try decoder.decode(Root.self, from: data)
                completion(root.unixtime, TimeZone(identifier: root.timezone), nil)
            } catch {
                completion(nil, nil, error)
            }
        }.resume()
    }
}

Usage:用法:

URL.asyncTime { date, timezone, error in
    guard let date = date, let timezone = timezone else {
        print("Error:", error ?? "")
        return
    }
    print("Date:", date.description(with: .current))  // "Date: Tuesday, July 28, 2020 at 4:27:36 AM Brasilia Standard Time\n"
    print("Timezone:", timezone)   // "Timezone: America/Sao_Paulo (current)\n"
}

If you want the current date of the user, you can simply implement let date = Date() .如果你想要用户的当前日期,你可以简单地实现let date = Date() It will return the date used on the users device.它将返回用户设备上使用的日期。

This for example will be displayed for me例如,这将为我显示

let date = Date() // Jul 28, 2020 at 8:22 AM
var timezone = TimeZone.current // Europe/Berlin (current)

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

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