Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift how to have DateFormatter without year for any locale?

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)
like image 753
Alex Stone Avatar asked Jan 02 '23 04:01

Alex Stone


1 Answers

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.

like image 133
rmaddy Avatar answered Jan 05 '23 19:01

rmaddy