Skip to content

Instantly share code, notes, and snippets.

@ashikahmad
Last active February 4, 2019 16:29
Show Gist options
  • Save ashikahmad/b2d303e2fc751ab62ce9f94347bdf611 to your computer and use it in GitHub Desktop.
Save ashikahmad/b2d303e2fc751ab62ce9f94347bdf611 to your computer and use it in GitHub Desktop.
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("")
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment