dypbrg
dypbrg

Reputation: 773

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

which is supposed to be: 01/01/1970 00:00:00

what could be wrong?

Upvotes: 0

Views: 330

Answers (2)

Shahzaib Qureshi
Shahzaib Qureshi

Reputation: 920

Try this and you will get the date according to your 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)

Upvotes: 1

Martin R
Martin R

Reputation: 539765

  • Date(timeIntervalSince1970:) creates a date relative to 00:00:00 UTC on 1 January 1970 by the given number of seconds.
  • DateFormatter by default formats the date according to your local timezone.

Apparently you are in the GMT+8 timezone, so "00:00:00 UTC" is "08:00:00" on your clock.

You can assign a different timezone to the date formatter if required. To print the formatted date relative to UTC use

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

Upvotes: 1

Related Questions