hello can any one point me to hoe make a date format that looks like this: 13th June 2007. Notice the day has the word "th". I want to add that in my format. Thanks!
Asked
Active
Viewed 7,744 times
7
-
have you not googled this? – Jessedc May 31 '16 at 03:02
-
Loosely related (not the same question): http://stackoverflow.com/questions/31686225/date-time-natural-language-approximation-in-swift?rq=1 – Thilo May 31 '16 at 06:06
-
You might note that this is not a common format. While the ordinal suffix (`th`) is read, it is not usually written. The standard format is "13 June 2007" or "June 13, 2007". Usually you want to use the system formatting patterns that will decide this for you. – Sulthan May 31 '16 at 07:52
1 Answers
22
Updated for Swift 3
You can do something like this which is locale safe.
let calendar = Calendar.current
let date = Date()
let dateComponents = calendar.component(.day, from: date)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
let day = numberFormatter.string(from: dateComponents as NSNumber)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM yyyy"
let dateString = "\(day!) \(dateFormatter.string(from: date))"
print(dateString)

Desdenova
- 5,326
- 8
- 37
- 45
-
Unfortunately, some languages don't use ordinals in their dates. For example, this works for English, but would fail in Spanish (.° is not used in dates). – jowie Oct 28 '20 at 12:36
-
A Colombian-American colleague tells me that Spanish uses ordinal for the first of the month but not others, so "1st of December" would be spoken as "primero de diciembre" but "2nd of December" would spoken as "dos de diciembre" – Duncan C Jun 04 '21 at 13:38