简体   繁体   English

使用timeIntervalSince1970时DateFormatter结果不正确

[英]Incorrect DateFormatter result when using timeIntervalSince1970

When I run the following code 当我运行以下代码

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
print(dateFormatter.string(from: Date(timeIntervalSince1970: 0)))

This gets printed out: 01/01/1970 08:00:00 打印出来: 01/01/1970 08:00:00

which is supposed to be: 01/01/1970 00:00:00 应该是: 01/01/1970 00:00:00

what could be wrong? 有什么问题吗?

  • Date(timeIntervalSince1970:) creates a date relative to 00:00:00 UTC on 1 January 1970 by the given number of seconds. Date(timeIntervalSince1970:)以给定的秒数创建一个相对于1970年1月1日UTC时间00:00:00的日期。
  • DateFormatter by default formats the date according to your local timezone. 默认情况下, DateFormatter根据您的本地时区格式化日期。

Apparently you are in the GMT+8 timezone, so "00:00:00 UTC" is "08:00:00" on your clock. 显然,你是在GMT + 8时区,所以“00:00:00 UTC”是“08:00:00” 你的时钟。

You can assign a different timezone to the date formatter if required. 如果需要,可以为日期格式化程序分配其他时区。 To print the formatted date relative to UTC use 打印相对于UTC使用的格式化日期

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // <--- HERE
print(dateFormatter.string(from: Date(timeIntervalSince1970: 0)))

Try this and you will get the date according to your TimeZone : 试试这个,您将根据您的TimeZone获得日期:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let timeZoneDifference = TimeInterval(TimeZone.current.secondsFromGMT())
let date = dateFormatter.string(from: Date(timeIntervalSince1970: 0))
print(date)
let dateAccoringToMyTimeZone = dateFormatter.string(from: 
Date(timeIntervalSince1970: timeZoneDifference))
print(dateAccoringToMyTimeZone)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM