【问题标题】:Date() shows wrong time [duplicate]Date() 显示错误的时间[重复]
【发布时间】:2020-03-15 02:46:04
【问题描述】:

我将这个库用于日历:https://github.com/CVCalendar/CVCalendar

我尝试获取用户当前的日期和时间,以便在日历中显示正确的日期。

但是当我尝试做print("Date: \(Date())") 时,我得到了这个输出:

2019-11-19 14:32:03 +0000

但如果这是正确的,它应该是这样的:

2019-11-19 15:32:03 +0000

(我住在挪威)。所以它给了我 1 个小时的错误。

有什么建议吗?

【问题讨论】:

标签: ios swift xcode


【解决方案1】:

来自Apple's documentation

日期独立于特定的日历或时区。到 向用户表示日期,您必须在上下文中解释它 日历。

你需要Calendar的帮助:

let calendar = Calendar(identifier: .gregorian)
let currentDate = Date()
print(calendar.dateComponents(in: calendar.timeZone, from: currentDate))

输出将是:

calendar: gregorian (fixed) timeZone: Europe/Bratislava (current) era: 1 year: 2019 
month: 11 day: 19 hour: 15 minute: 47 second: 14 nanosecond: 285109996 weekday: 3 weekdayOrdinal: 3 quarter: 0 weekOfMonth: 4 weekOfYear: 47 yearForWeekOfYear: 2019 isLeapMonth: false 

这样您就可以访问您的calendar 的组件,例如hourminute 等。

更新:

@Camile 在 cmets 中使用 DateFormatter 回答了他们的问题:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
dateFormatter.timeZone = calendar.timeZone
dateFormatter.string(from:currentDate)

会给你

2019-11-19 16:38:03:+0100

【讨论】:

  • 我怎样才能以这种格式存储它:2019-11-19 15:32:03 +0000
  • 我试过这个; pastebin.com/GH9BEeRx - 它似乎有效。
  • @Camile 请检查时区的 dateFormat 字符串dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss:Z"
  • 额外的;如何将输出转换回Date()
  • @Camile let formattedDate = dateFormatter.string(from:currentDate) let newDate = dateFormatter.date(from: formattedDate) 你会再次得到时区独立结果:2019-11-19 16:29:55 +0000,见第一段答案
猜你喜欢
  • 2017-02-17
  • 2011-02-14
  • 2013-02-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多