SquareBox
SquareBox

Reputation: 839

Set global TimeZone for DateFormatter

I searched here in SO but can't find useful thread to accomplish what I want. I'm new with Swift so I don't know much of this. So the scenario is I want to set a specific timezone which can be change by user with the app's settings. What I want is when the user changed the said timezone it should reflect through out the app. Yes I can set the timezone in each "DateFormatter" but I don't want to write it every time I create a DateFormatter.

Is there a way so when I create an instance of the DateFormatter the timezone is already set to the timezone the user selected? Is it possible to do this using an Extension of the DateFormatter?

Upvotes: 0

Views: 5910

Answers (1)

Nirav D
Nirav D

Reputation: 72410

What you can do is make extension of Date as of you are setting this TimeZone to DateFormatter to formate your date, So make two extension one for Date and one for String.

extension Date {

    struct CustomDateFormatter {

        static var currentTimeZone = TimeZone.current //Set default timeZone that you want

        static func dateFormatter(withFormat format: String) -> DateFormatter {
            let formatter = DateFormatter()
            formatter.timeZone = CustomDateFormatter.currentTimeZone
            formatter.dateFormat = format
            return formatter
        }            
    }

    func toDateString(withFormat format: String) -> String {
        return CustomDateFormatter.dateFormatter(withFormat: format).string(from: self)
    }
}

extension String {
    func toDate(withFormat format: String) -> Date? {
        return Date.CustomDateFormatter.dateFormatter(withFormat: format).date(from:  self)
    }
}

Now when ever you need to set TimeZone or want to convert Date to String or vice versa use this extension like this.

//Set timezone
Date.CustomDateFormatter.currentTimeZone = TimeZone(abbreviation: "GMT")!
//get date from String
let date = "31-05-2017 07:30:05".toDate(withFormat: "dd-MM-yyyy HH:mm:ss")
//get string from date with specific format
let dateString = Date().toDateString(withFormat: "dd-MM-yyyy HH:mm:ss")

Upvotes: 3

Related Questions