How can I get current GMT 0 in Swift 3?
Asked Answered
O

3

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?

Okelley answered 29/12, 2016 at 16:17 Comment(4)
Requesting current time wouldn't return gmt-0 time for me. I don't understand your point.Okelley
You should change your dateFormat to include the Z (timezone) in your final String otherwise the user or developer would not know it is not local time.Defective
You should also set your date formatar locale to en_US_POSIX and calendar to iso8601.Defective
https://mcmap.net/q/115683/-how-can-i-parse-create-a-date-time-stamp-formatted-with-fractional-seconds-utc-timezone-iso-8601-rfc-3339-in-swiftDefective
G
29

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

formatter.timeZone = TimeZone(secondsFromGMT:0)

Or this line:

formatter.timeZone = TimeZone(identifier:"GMT")
Glaciate answered 29/12, 2016 at 16:25 Comment(0)
S
1

add this extension to Date this will convert any Timezone to to GMT+/-

extension Date {
func getFormattedTimeZone() -> String {
        let timeZone = TimeZone.current
        let seconds = timeZone.secondsFromGMT(for: self)
        let hours = abs(seconds) / 3600
        let minutes = abs(seconds) / 60 % 60
        
        let formattedHours = String(format: "%02d", hours)
        let formattedMinutes = String(format: "%02d", minutes)
        let sign = seconds >= 0 ? "+" : "-"
        
        return "GMT\(sign)\(formattedHours):\(formattedMinutes)"
    }

}

Example use

    let date = Date() //2024-07-19 07:53:20 +0000
    let currentTimezone = TimeZone.current.abbreviation() //GST 
    let timezone = date.getFormattedTimeZone() //GMT+4:00
Siskind answered 19/7, 2024 at 8:9 Comment(0)
O
-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()
}

}

Openwork answered 25/6, 2023 at 21:40 Comment(1)
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.Oruntha

© 2022 - 2025 — McMap. All rights reserved.