Last active
February 4, 2019 16:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//---------------------------------------------------------- | |
// 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