Home > database >  How to get the current time in a specific timezone?
How to get the current time in a specific timezone?

Time:12-01

I am currently working on an app where I have the necessity to get the current date and time in the Europe/Rome timezone. I have created the following method to do so:

static func getItalianDate() -> Date {
    let timezone = TimeZone(identifier: "Europe/Rome")!
    let seconds = TimeInterval(timezone.secondsFromGMT(for: Date()))
    let date = Date(timeInterval: seconds, since: Date())

    return date
}

This however won't return the correct value in case the user manipulates the date and timezone from the settings General -> Date and Time and I can't figure out how to get the correct answer. The format I need is something like: "yyyy-MM-dd HH:mm:ss".

Any suggestion?

EDIT

I found this question - still unanswered - with the same problem I am facing here. Is using a server the only option available?

CodePudding user response:

let dateFormatter = {
    var df = DateFormatter()
    df.timeZone = Calendar.current.timeZone
    df.dateFormat = ”yyyy-MM-dd HH:mm:ss”
    return df
}()

let timestamp = dateFormatter.string(from: date)
// display your timestamp

In case you your app needs to refresh its view upon timezone changes (hence recalculate the timestamp to display), either react to NSSystemTimeZoneDidChange notification in case is UIKit based or use the SwiftUI environment timeZone global variable in case its view is SwiftUI based.

CodePudding user response:

import Foundation

// 1. Choose a date
let today = Date()

// 2. Pick the date components
let hours   = (Calendar.current.component(.hour, from: today))
let minutes = (Calendar.current.component(.minute, from: today))
let seconds = (Calendar.current.component(.second, from: today))

// 3. Show the time
print("\(hours):\(minutes):\(seconds)") 
  • Related