I want to create a date string from two dates in format like :
"Apr 21 - Sep 17, 2018" - US
"21 Apr - 17 Sep, 2018" - Elsewhere
While respecting local date formats (MMM dd for US, dd MMM for Europe, etc).
How do I get the DateFormatter to give me the default style but without year?
let startDateFormatter = DateFormatter()
// How to keep medium style but without year?
// this is the US style,
// I want locale-independent style to match the other date formatter
startDateFormatter.dateFormat = "MMM dd"
let endDateFormatter = DateFormatter()
endDateFormatter.dateStyle = .medium
endDateFormatter.timeStyle = .none
let startDateText = startDateFormatter.string(from: startDate)
let endDateText = endDateFormatter.string(from: endDate)
Use DateIntervalFormatter
. This is designed to give you a properly localized string representing a date interval between two dates.
Here is an example with your two dates:
// Test code for the two dates
let firstDate = Calendar.current.date(from: DateComponents(year: 2018, month: 4, day: 21))!
let lastDate = Calendar.current.date(from: DateComponents(year: 2018, month: 9, day: 17))!
let dif = DateIntervalFormatter()
dif.timeStyle = .none
dif.dateStyle = .medium
let dateInt = dif.string(from: firstDate, to: lastDate)
Result (US):
Apr 21 – Sep 17, 2018
Result (UK):
21 Apr – 17 Sep 2018
Incase you ever do need to use DateFormatter
with a specific dateFormat
that is properly localized (such as month and day but no year), use setLocalizedDateFormatFromTemplate
.
let df = DateFormatter()
df.setLocalizedDateFormatFromTemplate("MMMdd")
let result = df.string(from: Date())
This will give a properly localized result containing just the day and abbreviated month.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With