Swift DateFormatter returning tomorrow's date even after setting the Locale and Timezone

55 Views Asked by At

I'm using DateFormatter from Swift to show date to users in "yyyy.MM.dd" format. I find one thing very strange that even after I've set the Timezone, it gives me the date a day after.

let formatter = DateFormatter()
formatter.dateFormat = "yyyy.MM.dd"
formatter.locale = Locale(identifier: "ko_kr")
formatter.timeZone = TimeZone(abbreviation: "KST")

let date = formatter.string(from: myDate)

myDate above is like 2023-06-29 18:25:13 +0000 For example, today is 2023.06.29 and it should return 2023.06.29 but it returns 2023.06.30.

Is there any other parts that I should look into?

2

There are 2 best solutions below

0
Anton Agafonov On

You can set the defaultTimeZone property of the DateFormatter explicitly to the desired time zone (KST) using the TimeZone(abbreviation: "KST"). This ensures that the DateFormatter consistently uses the specified time zone when formatting the date, instead of relying on the device's default time zone.

    if let timeZone = TimeZone(abbreviation: "KST") {
    formatter.defaultTimeZone = timeZone
}
0
Rajni Bajaj On

There is no issue with the above code. I have tried with all the possible cases but the above code is returning the correct date.