如何在 swift 中获取当前的 UTC 时间
How to get currentUTC time in swift
我想在 swift 中设置倒数计时器。我有一个选项是获取当前时间是 Date(),但是当我的设备时间设置错误时,此方法给出了错误的日期时间。
是否可以在 swift 中获取准确的当前 UTC 时间,所以我将设置倒数计时器,并保留准确的时间。
谢谢。
Date
class 没有时区,它只是一个 "point int the time line",所有时区都一样。当您使用 DateFormatter
将日期转换为字符串(或将字符串转换为日期)时,您可以像这样指定时区:
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
如果您不相信设备日期,您将不得不使用这样的 NTP 服务:
https://github.com/instacart/TrueTime.swift
https://github.com/jbenet/ios-ntp
Get Date and Time from Apple Server
很多次,我遇到过同样的问题,如果用户更改了他的当前时间,那么很多逻辑都会打扰,不幸的是,运气不好,因为 Date()
总是 returns 你的设备日期。
知名游戏Candy crush,点数满了不能玩特定时间,但是如果我把设备时间改成功能时间就全部解锁了。这是您问题的最佳示例。
You can use below-given web service or your web service to achieve your requirements. Below are some
free API's which provides date and time.
除了其他答案,您还可以为 Date class 编写扩展以获取特定 TimeZone 中的格式化数据,使其成为实用函数以备将来使用。喜欢
extension Date {
func dateInTimeZone(timeZoneIdentifier: String, dateFormat: String) -> String {
let dtf = DateFormatter()
dtf.timeZone = TimeZone(identifier: timeZoneIdentifier)
dtf.dateFormat = dateFormat
return dtf.string(from: self)
}
}
现在你可以这样称呼它了
Date().dateInTimeZone(timeZoneIdentifier: "UTC", dateFormat: "yyyy-MM-dd HH:mm:ss");
我想在 swift 中设置倒数计时器。我有一个选项是获取当前时间是 Date(),但是当我的设备时间设置错误时,此方法给出了错误的日期时间。
是否可以在 swift 中获取准确的当前 UTC 时间,所以我将设置倒数计时器,并保留准确的时间。
谢谢。
Date
class 没有时区,它只是一个 "point int the time line",所有时区都一样。当您使用 DateFormatter
将日期转换为字符串(或将字符串转换为日期)时,您可以像这样指定时区:
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
如果您不相信设备日期,您将不得不使用这样的 NTP 服务:
https://github.com/instacart/TrueTime.swift
https://github.com/jbenet/ios-ntp
Get Date and Time from Apple Server
很多次,我遇到过同样的问题,如果用户更改了他的当前时间,那么很多逻辑都会打扰,不幸的是,运气不好,因为 Date()
总是 returns 你的设备日期。
知名游戏Candy crush,点数满了不能玩特定时间,但是如果我把设备时间改成功能时间就全部解锁了。这是您问题的最佳示例。
You can use below-given web service or your web service to achieve your requirements. Below are some free API's which provides date and time.
除了其他答案,您还可以为 Date class 编写扩展以获取特定 TimeZone 中的格式化数据,使其成为实用函数以备将来使用。喜欢
extension Date {
func dateInTimeZone(timeZoneIdentifier: String, dateFormat: String) -> String {
let dtf = DateFormatter()
dtf.timeZone = TimeZone(identifier: timeZoneIdentifier)
dtf.dateFormat = dateFormat
return dtf.string(from: self)
}
}
现在你可以这样称呼它了
Date().dateInTimeZone(timeZoneIdentifier: "UTC", dateFormat: "yyyy-MM-dd HH:mm:ss");