-1

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

User123
  • 51
  • 1
  • 7

1 Answers1

1

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?

Matic Oblak
  • 16,318
  • 3
  • 24
  • 43
  • 1
    @User123 Out of scope but even better would be `"dd'\(daySuffix(from: date1)) 'MMMM', 'yyyy"` Note adding `''` for other parts as well. It should not impact your output because spaces and comas are ignored. But to be safe it is best to always use `''`. – Matic Oblak Feb 16 '22 at 12:48