ashikahmad
7/19/2017 - 1:26 PM

A Playground (swift code) to show a workaround of day ordinal (Ex: `1st` February) with DateFormatter

A Playground (swift code) to show a workaround of day ordinal (Ex: 1st February) with DateFormatter


//----------------------------------------------------------
// NOTE:
// Paste this files content to a playground to experiment
//----------------------------------------------------------

import UIKit


func dateStr(_ format: String, date: Date = Date())-> String {
    let formatter = DateFormatter()
    formatter.dateFormat = format
//    let date = Date()
    var str = formatter.string(from: date)
    if str.contains("<dth>") {
        str = str.replacingOccurrences(of: "<dth>", with: ordinal(for: date))
    }
    return str
}

func ordinal(for date: Date) -> String {
    let num = NumberFormatter()
    num.numberStyle = .ordinal
    let day = Calendar.current.component(.day, from: date)
    let ordinal = num.string(from: NSNumber(value: day)) ?? ""
    return ordinal
}

//dateStr("y/MM/dd '<dth>' B")



let formatter = DateFormatter()
formatter.dateFormat = "MM dd yy"
let dt = formatter.date(from: "01 1 17")!

dateStr("'<dth>' MMMM, yyyy", date: dt)


//for ch in "abcdefghijklmnopqrstuvwxyz".characters {
//    let str = String([ch])
//    for m in 1..<10 {
//        var s = str.padding(toLength: m, withPad: str, startingAt: 0)
//        print("\(m): \(s) \(dateStr(s))")
//    }
//    print("")
//}