-1

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?

4
  • 1
    2023-06-29 18:25:13 +0000 is indeed 2023-06-30 in Korea. Try adding 9 hours (Korea's offset) to 18:25:13. It'd go into the next day. Commented Jun 29, 2023 at 9:34
  • @Sweeper Hi thanks for the comment. Then is it possible even without setting the timezone, the device itself sets the timezone to KST? Because it had same issue without the timezone code. Commented Jun 30, 2023 at 0:39
  • Yeah, IIRC if your device is in KST, then it is automatically set to KST. Commented Jun 30, 2023 at 0:43
  • @Sweeper Oh now I understand. I see the mistake now. Thanks! Commented Jun 30, 2023 at 0:46

2 Answers 2

0

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.