我想要获得没有时间的今天日期,因此我可以使用它与从 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)!
Run Code Online (Sandbox Code Playgroud)
但我对时区有一个奇怪的问题。例如,今天是16/09/17,但最终今天将等于
2017-09-15 23:00:00 世界标准时间
解决这个问题的唯一方法实际上是将我的时区指定为 GMT。
components.timeZone = NSTimeZone(name: "GMT")! as TimeZone
Run Code Online (Sandbox Code Playgroud)
那么结果就是正确的。
2017-09-16 00:00:00 世界标准时间
为什么你需要指定时区,因为它已经应该由 dateComponents 设置或者我做错了什么。
在设置我自己的时区之前,它等于 NSTimeZone“欧洲/伦敦”
时区“欧洲/伦敦”目前对应于“BST”,即英国夏令时间,即 GMT+1,因此您会看到问题。
DateFormatter当使用 a并将其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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8192 次 |
| 最近记录: |