使用带有TimeZone的DateFormatter来格式化Swift中的日期

时间:2018-04-26 22:44:38

标签: swift swiftdate

如何解析只有日期信息的日期(没有时间),例如2018-07-24

我正在尝试

let dateFormatter = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd"
dateFormatter.dateFormat = dateFormat
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

dateFormatter.date(from: "2018-07-24")
  

打印第23天

看起来它使用00:00:00作为默认时间,然后将其转换为前一天的UTC结果...

我该如何改变?

1 个答案:

答案 0 :(得分:1)

似乎您将格式化程序的时区设置为UTC,然后尝试在当地时区获取当天。

如果您使用此代码 - 您将看到第24天

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")

let date = dateFormatter.date(from: "2018-07-24")

print(dateFormatter.string(from: date!)) // prints "2018-07-24"

但是如果您使用“日历”从日期获取日期组件,您将获得带有时区偏移的日期。

因此,例如在我的时区,我使用此代码看到第24天(GMT + 02)

var calendar = Calendar.current
let day = calendar.component(.day, from: date!)
print(day) // prints 24

但如果我在美国的某个地方设置日历的时区,我会看到第23天

var calendar = Calendar.current
calendar.timeZone = TimeZone.init(abbreviation: "MDT")!
let day = calendar.component(.day, from: date!)
print(day) // prints 23

因此日历使用您的本地时区从日期获取组件

因此,如果您需要从日期获取日期组件,请使用您用于从字符串中解析日期的相同时区。

var calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "UTC")!
let day = calendar.component(.day, from: date!)
print(day) // prints 24