Search code examples
iosswiftswift3nsdatensdateformatter

Change the NSDate formatter to convert string to desired style


How to change the date formatter of 1st Dec 1984 String value to 2022-12-01

What will be the required Date formatter style?


Solution

  • This answer isn't pretty by any means. But it will get the job done. What's difficult is the 'st' in 1st. As far as I know there isn't a date format for that.

    let dateString = "1st Dec 1984".replacingOccurrences(of: "[st|nd|th|rd]", with: "", options: .regularExpression)
    let formatter = DateFormatter()
    
    formatter.dateFormat = "d MM yyyy"
    
    let date = formatter.date(from: dateString)
    
    formatter.dateFormat = "yyyy-MM-dd"
    
    let newString = formatter.string(from: date!)
    

    This will give you your desired results. Except I'm not sure how you get the 2022 in your result since that can never be produced from your given date.