Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add daySuffix to day using dateformatter in Swift

I am getting daySuffix with below code

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

I am using DateFormatter to show JSON date in Label like below. In this code because of dateFormatter.dateFormat = "dd'th' MMMM, yyyy" this line for all suffix I am only getting th how to use daySuffix method to date, someone please guide me

let fromDateString = enquiryData.from_date//vale from JSON

var fromDate: String?

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"

let date1 = dateFormatter.date(from: fromDateString!)
if let date1 = date1 {

dateFormatter.dateFormat = "dd'th' MMMM, yyyy"
fromDate = dateFormatter.string(from: date1)

dateLbl.text = fromDate ?? ""
}

// prints exact day suffix
let testDate = daySuffix(from: date1!)
print("daySuffix value \(testDate)")// this prints exact suffix

here if i print let testDate = daySuffix(from: date1!) print("daySuffix value \(testDate)") prints exact suffix but how do i add suffix to date

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When using date formatter all characters within '' will be ignored and kept unformatted. So you simply need to do

dateFormatter.dateFormat = "dd'\(daySuffix(from: date1))' MMMM, yyyy"

or does this not work for you?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading