6

I have to display date in different format.

For eg. 21st July

I didn't find anything to convert my date in this format. If anyone knows please help me.

Abha
  • 1,032
  • 1
  • 13
  • 36
  • Possible duplicate of [Formatting Date to dd-MMM in iOS](http://stackoverflow.com/questions/10574248/formatting-date-to-dd-mmm-in-ios) – Shaik Riyaz Mar 02 '16 at 06:29

3 Answers3

19

Swift

extension Date {

    func dateFormatWithSuffix() -> String {
        return "dd'\(self.daySuffix())' MMMM yyyy"
    }

    func daySuffix() -> String {
        let calendar = Calendar.current
        let components = (calendar as NSCalendar).components(.day, from: self)
        let dayOfMonth = components.day
        switch dayOfMonth {
        case 1, 21, 31:
            return "st"
        case 2, 22:
            return "nd"
        case 3, 23:
            return "rd"
        default:
            return "th"
        }
    }
}

Example

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = date.dateFormatWithSuffix()
print(dateFormatter.string(from: date))
// Output for current date: 22nd May 2019
Darkngs
  • 6,381
  • 5
  • 25
  • 30
  • 2
    This is not language agnostic. You could use `NumberFormatter` with `.numberStyle = ordinal` but then some languages also don't expect an ordinal style in their dates. – jowie Oct 28 '20 at 12:35
  • @jowie you are correct! I answered to primary question regarding "st", "nd", "rd" and "th". For other languages it is complicated) – Darkngs Dec 23 '20 at 20:09
12
    func setCurrentDate() {
        let date = Date()

        // Use this to add st, nd, th, to the day
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .ordinal
        numberFormatter.locale = Locale.current

        //Set other sections as preferred
        let monthFormatter = DateFormatter()
        monthFormatter.dateFormat = "MMM"

        // Works well for adding suffix
        let dayFormatter = DateFormatter()
        dayFormatter.dateFormat = "dd"

        let dayString = dayFormatter.string(from: date)
        let monthString = monthFormatter.string(from: date)

        // Add the suffix to the day
        let dayNumber = NSNumber(value: Int(dayString)!)
        let day = numberFormatter.string(from: dayNumber)!

        yourDateLabel.text = "\(day) \(monthString)"
}

Label will currently be set to 25th May

Waylan Sands
  • 321
  • 3
  • 11
-3

You can use NSDateFormatter to display your NSDate. It has properties such as dateStyle, and timeStyle which can easily be altered to get your desired format. If you need more flexibility there's the dateFormat property as well.

    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    formatter.stringFromDate(NSDate()) 
Julian J. Tejera
  • 1,015
  • 10
  • 17