在这里,我想使用一些特定城市的时区来获取当前的Hour/Minute/Secong/Millisecond,比如使用America/Mexico_City的3Xcode。我试着弄到墨西哥城现在的时间-小时/分钟/秒/毫厘,
let date = Date()
var calendar = Calendar.current
calendar.timeZone = TimeZone.init(identifier: "America/Mexico_City")! /* Something wrong here */
hrOfDay = calendar.component(.hour, from: date)
curMin = calendar.component(.minute, from: date)
curSec = calendar.component(.second, from: date)
curMillSec = Int(Int64(Date().timeIntervalSince1970 * 1000)) /* this should be fetched using calendar object */
print("hours = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")但我无法了解像MexicoCity这样的特定城市的当前时间。所以请帮帮我。
发布于 2017-11-16 10:38:17
TimeZone.init(标识符:“America/墨西哥城”)
“美国/墨西哥城”是ID,不是名字。
因此,您可以比较从list获得TimeZone ID的城市名称:
https://raw.githubusercontent.com/dmfilipenko/timezones.json/master/timezones.json参考文献:https://github.com/dmfilipenko/timezones.json
发布于 2017-11-16 16:46:03
终于解决了
步骤1:使用此链接的查找城市/国家缩写abbr。
步骤2:使用步骤1中提到的链接,您将获得JsonObject作为响应,如墨西哥城的示例:
{
"value": "Central Standard Time (Mexico)",
"abbr": "CDT",
"offset": -5,
"isdst": true,
"text": "(UTC-06:00) Guadalajara, Mexico City, Monterrey",
"utc": [
"America/Bahia_Banderas",
"America/Cancun",
"America/Merida",
"America/Mexico_City",
"America/Monterrey"
]
}步骤3:因此使用这个缩写键值,如TimeZone.init(缩写:"CDT"),如下所示。
func initVars(){
var date = Date()
var calendar = Calendar.current
calendar.timeZone = TimeZone.init(abbreviation: "CDT")!
hrOfDay = calendar.component(.hour, from: date)
curMin = calendar.component(.minute, from: date)
curSec = calendar.component(.second, from: date)
curMillSec = calendar.component(.nanosecond, from: date) // may need to convert NANOSECOND to Millisecond // this should be fetchhed using calendat obj
print("TESTING Current Time = \(hrOfDay):\(curMin):\(curSec):\(curMillSec)")
},所以最后是,因此您将得到如下所示:
TESTING Current Time = 10:39:17:812892973墨西哥时间:2017年11月16日(星期四)上午10:39 (科技委)墨西哥城CDMX,墨西哥
https://stackoverflow.com/questions/47323036
复制相似问题