swift - 使用 Calendar.date 时时区错误

标签 swift date swift3

我想获得一个没有时间的今天日期,所以我可以用它来与我从 API 获得的其他日期对象进行比较。

这是我的代码:

var today = Date()
let gregorian = Calendar(identifier: .gregorian)
var components = gregorian.dateComponents([.timeZone, .year, .month, .day, .hour, .minute,.second], from: today)

components.hour = 0
components.minute = 0
components.second = 0

today = gregorian.date(from: components)!

但是我在时区方面遇到了一个奇怪的问题。例如,今天是 16/09/17,但最终今天将等于

2017-09-15 23:00:00 UTC

解决这个问题的唯一方法实际上是将我的时区指定为 GMT。

components.timeZone = NSTimeZone(name: "GMT")! as TimeZone

那么结果就是正确的。

2017-09-16 00:00:00 UTC

为什么你需要指定时区,因为它已经应该由 dateComponents 设置或者我做错了什么。
在设置我自己的时区之前,它等于 NSTimeZone "Europe/London"

最佳答案

时区“欧洲/伦敦”目前对应于“BST”,即英国夏令时间,即 GMT+1,因此您会遇到问题。

当使用 DateFormatter 并将其 timeStyle 设置为 .full 时,您可以看到这一点。

let df = DateFormatter()
df.timeZone = TimeZone(identifier: "Europe/London")
df.dateStyle = .medium
df.timeStyle = .full
print(df.string(from: Date())) // "Sep 16, 2017, 4:56:55 PM British Summer Time"
df.timeZone = TimeZone.current //I am actually in London, so this will be the same as explicitly setting it to Europe/London
print(df.string(from: Date())) // "Sep 16, 2017, 4:56:55 PM British Summer Time"
df.timeZone = TimeZone(abbreviation: "UTC")
print(df.string(from: Date())) // "Sep 16, 2017, 3:56:55 PM GMT"

关于swift - 使用 Calendar.date 时时区错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46255593/

相关文章:

ios - 如何制作一个可扩展的 tableview 来显示 iOS 的其余细节?

ios - 如何在另一个 .swift 文件中调用变量属性?

swift - 如何在 Swift 中获取 CString (UTF8String) 的长度?

ios - 是否 URLSession.dataTask(与 :completionHandler:) always call completionHandler only once?

javascript - 与日期对象相乘 - javascript

sql-server - TryParse SSIS 忽略源行

objective-c - 如何停止在每次函数调用时都创建新字典以减少内存使用量?

ios - 我可以使用 MetalKit 在 GPU 上编码和解码 JSON 吗?

php - 将日期字符串转换为日期

ios - 如何在 iOS 版 Google map 中添加自定义数据以叠加?