【问题标题】:Correct date time according to device location india or usa根据设备位置印度或美国更正日期时间
【发布时间】:2018-02-15 12:32:08
【问题描述】:

我想根据我正在使用昨天给我的代码的 iPhone 设备获取当前时间。 我的代码是

let calendar = Calendar.current
let dateStart = calendar.startOfDay(for: Date())


let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.timeZone = TimeZone.current
let strDate = Date().description(with: Locale.current) //dateFormatter.string(from: dateStart)

print("日期开始 ***** (dateStart)")

我收到了回复:

开始日期 ***** 2018-02-14 18:30:00 +0000

谁能帮助我今天的正确时间是 15-02-2018 18:00

谢谢

【问题讨论】:

标签: ios swift nsdateformatter nstimezone


【解决方案1】:

试试这个:

let calendar = Calendar.current
let dateStart = calendar.startOfDay(for: Date()) // Feb 15, 2018 at 12:00 AM"
print(dateStart) // 2018-02-14 18:30:00 +0000

let dateFormatter = DateFormatter()
var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "UTC" }
dateFormatter.locale = Locale.init(identifier: localTimeZoneAbbreviation)
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let newDate = dateFormatter.string(from: dateStart)
print(newDate) //  2018-02-15 00:00

更新:

// Current Time  
dateStart = Date() 
newDate = dateFormatter.string(from: dateStart)
print(newDate) //  2018-02-15 22:30

【讨论】:

  • 感谢您的回答,它给了我正确的日期但不正确的时间。它总是给我00:00。
  • 因为calendar.startOfDay(for: Date()) 是 2018-02-14 18:30:00 +0000 表示 2018 年 2 月 15 日凌晨 12:00,即 24 小时 00:00
  • 在 24 小时内 calendar.startOfDay(for: Date()) 总是从 00:00 开始。
  • 好的,但我也需要当前正确的时间。我如何获得它?
  • let dateStart = Date() 获取当前时间为 2018-02-15 11:30 格式。 Ans 已更新为当前时间
猜你喜欢
  • 1970-01-01
  • 2020-01-20
  • 1970-01-01
  • 2010-11-14
  • 2018-03-06
  • 2021-05-06
  • 2018-09-07
  • 2013-05-29
  • 1970-01-01
相关资源
最近更新 更多