teradyl
teradyl

Reputation: 2802

How to format a date range (with only one year string) in different locale's in iOS?

The date string in English: Jan 18 - Jan 26, 2018

Incorrect Korean date string: Jan 18 - 2018 Jan 26

What should happen in Korean: 2018 Jan 18 - Jan 26 (not exactly correct Korean, just referring to the location of the year. See accepted answer to see proper Korean date format)

Right now this requires to date formatters, but you have to hardcode which date formatter has the year, so the Korean date doesn't look right.

Is this possible to do in Swift/Objc without just putting the year string on both sides of the date range?

Upvotes: 1

Views: 693

Answers (1)

rmaddy
rmaddy

Reputation: 318824

Use a DateIntervalFormatter:

let sd = Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 18))!
let ed = Calendar.current.date(from: DateComponents(year: 2018, month: 1, day: 26))!
let dif = DateIntervalFormatter()
dif.dateStyle = .medium
dif.timeStyle = .none
dif.locale = Locale(identifier: "en_US")
let resEN = dif.string(from: sd, to: ed)
dif.locale = Locale(identifier: "ko_KR")
let resKO = dif.string(from: sd, to: ed)

This results in:

Jan 18 – 26, 2018
2018. 1. 18. ~ 2018. 1. 26.

The output isn't exactly what you show in your question but the output is appropriate for the given locales.

Upvotes: 7

Related Questions