首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取当前时间/分钟/秒/毫秒使用某些特定城市的时区,如美国/墨西哥城市,在3xcode中

问获取当前时间/分钟/秒/毫秒使用某些特定城市的时区,如美国/墨西哥城市,在3xcode中
EN

Stack Overflow用户
提问于 2017-11-16 06:28:31
回答 2查看 296关注 0票数 0

在这里,我想使用一些特定城市的时区来获取当前的Hour/Minute/Secong/Millisecond,比如使用America/Mexico_City的3Xcode。我试着弄到墨西哥城现在的时间-小时/分钟/秒/毫厘,

代码语言:javascript
复制
    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这样的特定城市的当前时间。所以请帮帮我。

EN

回答 2

Stack Overflow用户

发布于 2017-11-16 10:38:17

TimeZone.init(标识符:“America/墨西哥城”)

“美国/墨西哥城”是ID,不是名字。

因此,您可以比较从list获得TimeZone ID的城市名称:

代码语言:javascript
复制
https://raw.githubusercontent.com/dmfilipenko/timezones.json/master/timezones.json

参考文献:https://github.com/dmfilipenko/timezones.json

票数 0
EN

Stack Overflow用户

发布于 2017-11-16 16:46:03

终于解决了

步骤1:使用此链接的查找城市/国家缩写abbr。

步骤2:使用步骤1中提到的链接,您将获得JsonObject作为响应,如墨西哥城的示例:

代码语言:javascript
复制
{
"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"),如下所示。

代码语言:javascript
复制
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)")

}

,所以最后是,因此您将得到如下所示:

代码语言:javascript
复制
TESTING Current Time = 10:39:17:812892973

墨西哥时间:2017年11月16日(星期四)上午10:39 (科技委)墨西哥城CDMX,墨西哥

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47323036

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档