Search code examples
iosswiftnsdateformatter

Getting different time formats on simulator and local devices - Swift iOS


Im trying to get a String date from Date() as shown below:

func today() -> String {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium

    return dateFormatter.string(from: date)
}

But the output diverse from when I'm running it on Simulator and local device:

On local device the output - "24 Nov 2019"

On Simulator iPhone 8 the output - "Nov 24, 2019"

*When I'm using date format from template ( such as "MMMMd-yyyy" ) the result still diverse from device to simulator.

Thank's in advance.


Solution

  • Reason you are getting different result is because the locale of your mac (Simulator) and your iPhone are different and DateFormatter depends on locale to turn date into string. when you don't give DateFormatter explicit locale it uses your device, so if you need same result, set locale.

    func today() -> String {
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .medium
        dateFormatter.locale = Locale(identifier: "en_US")
        return dateFormatter.string(from: date)
    }
    

    here's an interesting site to check different results. https://nsdateformatter.com