【问题标题】:Using DateFormatter with TimeZone to format dates in Swift在 Swift 中使用 DateFormatter 和 TimeZone 来格式化日期
【发布时间】:2018-04-26 22:44:37
【问题描述】:

如何解析只有日期信息(没有时间)的日期,例如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结果......

我该如何改变呢?

【问题讨论】:

  • 检查一下,希望对您有帮助:Date Format in Swift
  • 您是否希望将2018-07-24 视为用户的午夜区域设置时间、UTC 午夜或其他时区的午夜?
  • 你在哪里看到“23”?

标签: swift swiftdate


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 2020-04-04
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多