【问题标题】:DateFormatter is Giving a Day before date [duplicate]DateFormatter 给出日期前一天 [重复]
【发布时间】:2021-03-10 07:55:18
【问题描述】:

我正在使用以下代码来解析时间戳值。但是当我将它转换为日期时,它给出了正确的值(03-08-2021),但后来我尝试将此日期转换为字符串以满足我的要求。

但是该字符串导致了错误的值 03-07-2021。以下是我正在使用的代码。

    let epocTime = TimeInterval(1615161600000/1000)
    let date = Date(timeIntervalSince1970: epocTime)
    print(date)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.timeZone = .current
    dateFormatter.locale = .current
    let dateString = dateFormatter.string(from: date)
    print(dateString)

【问题讨论】:

  • 纪元时间戳通常采用 UTC 格式,print 始终以 UTC 格式显示日期。将第一行 print 替换为 print(date.description(with: .current))。现在日期表示将匹配。

标签: ios swift nsdateformatter


【解决方案1】:

您将Date(一个时间点)与格式化的日期字符串混合在一起,您可以在手表或日历上看到该字符串。 Date 始终引用 UTC(又名格林威治标准时间),因此 print(date) 的输出不会打印日历日期,而是 UTC 日期和时间。 如果您将该日期转换为“日历条目”(通过指定时区等),您将获得本地手表上显示的值,即 UTC 时间为 2021 年 3 月 8 日午夜。 如果您住在格林威治以西,这将是前一天,因为您仍然在 3 月 7 日,等待新的一天到来。

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 2013-11-05
    • 2016-02-24
    • 1970-01-01
    • 2010-10-19
    • 2020-08-24
    相关资源
    最近更新 更多