0

I have a date in string format as 2 January 2020 and I want to convert it as 2nd Jan, 2020.

I have tried with following code but of no use:

static func formatDateFromDateTimeString(dateString: String, inputFormat: String = "yyyy-MM-dd'T'HH:mm:ss", outPutFormat:String = "dd MMM yyyy | hh:mm a" )->String {
    let inputDateFormatter = DateFormatter()
    inputDateFormatter.dateFormat = inputFormat
    let date = inputDateFormatter.date(from: dateString)
    let outputDateFormatter = DateFormatter()
    outputDateFormatter.dateFormat = outPutFormat
    if let safeDate = date {
        return outputDateFormatter.string(from: safeDate)
    }
    return ""
}

formatDateFromDateTimeString(dateString: "2 January 2020")
pawello2222
  • 46,897
  • 22
  • 145
  • 209
A J
  • 441
  • 4
  • 20
  • I guess that you see that `date` is nil, no? Tell me: How does `"yyyy-MM-dd'T'HH:mm:ss"` match `"2 January 2020"`? And even if it did, how does `"dd MMM yyyy | hh:mm a"` match `"2nd Jan, 2020"` – Larme Oct 30 '20 at 09:36
  • actually my code is not working at all – A J Oct 30 '20 at 09:37
  • I think the desired format is not available in swift? – A J Oct 30 '20 at 09:44
  • https://stackoverflow.com/questions/31546621/display-date-in-st-nd-rd-and-th-format https://stackoverflow.com/questions/50655374/how-to-add-th-and-st-in-date-format but still, you don't even get `safeDate` yet. – Larme Oct 30 '20 at 09:50
  • how to call that function? – A J Oct 30 '20 at 09:54
  • 1
    Your desired format is wrong. You should attempt to use the formats that are commonly used (standardized), not create new formats unknown to users. Ideally, let the formatter decide the correct format depending on current language. – Sulthan Oct 30 '20 at 10:03

1 Answers1

2

DateFormatter doesn't support the ordinal date format 1st, 2nd you have to do it yourself for example

static func formatDateFromDateTimeString(dateString: String, inputFormat: String = "yyyy-MM-dd'T'HH:mm:ss") -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = inputFormat
    guard let date = dateFormatter.date(from: dateString) else { return nil }
    let day = Calendar.current.component(.day, from: date)
    dateFormatter.dateFormat = "MMM, yyyy"
    let numberFormatter = NumberFormatter()
    numberFormatter.numberStyle = .ordinal
    guard let dayString = numberFormatter.string(from: day as NSNumber) else { return nil }
    return dayString + " " + dateFormatter.string(from: date)
}

formatDateFromDateTimeString(dateString: "2 January 2020", inputFormat: "dd MMMM yyyy") 

The outPutFormat parameter makes no sense if you want this particular date format.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • 1
    By the way, `NumberFormatter` supports ordinals and you can use it for conversion. The reason why date formatter doesn't is the simple fact that such a format is wrong. – Sulthan Oct 30 '20 at 10:01