12

I'm looking for a way to display the current GMT-0 time.

So far, I've been doing it like:

    let UTCDate = Date()
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

    let defaultTimeZoneStr = formatter.string(from: UTCDate)

However it returns the current time of the phone.

How can I get the current GMT-0 time using Swift 3?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Machado
  • 14,105
  • 13
  • 56
  • 97

2 Answers2

28

Before the last line of your code, insert this line:

formatter.timeZone = TimeZone(secondsFromGMT:0)

Or this line:

formatter.timeZone = TimeZone(identifier:"GMT")
matt
  • 515,959
  • 87
  • 875
  • 1,141
-1
func findGMTDate(dateV: Date) -> Date {
let date = dateV
let dateFormatter = DateFormatter()

dateFormatter.timeZone = TimeZone(abbreviation: "GMT") // GMT or "UTC"
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateString = dateFormatter.string(from: date)

print("dateString: \(dateString)")

if let dateR = dateFormatter.date(from: dateString) {
    print(dateR)
    return dateR
} else {
    print("Date conversion failed")
    return Date()
}

}

  • This doesn't change anything. The date in and the date out are the same (at least to the whole second). It's pointless trying to convert a `Date` from one timezone to another. It's only relevant when you wish to convert a `Date` to a `String` for display to the user or for sending to some API that needs the date in a specific format. – HangarRash Jun 25 '23 at 22:46