Search code examples
iosswiftdatensdateformatter

Automated convert string into date


How can I automated convert string to date with this code

let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "HH:mm"

    guard let date = dateFormatter.date(from: String) else { return }

so I don't have to type again or reuse again, I was thinking with DateFormatter extension but I don't know how or is that the correct method. Thank you for your attention


Solution

  • You need to create extension on String instead of Dateformatter.

    Try with below code,

    extension String {
    
        var date: Date? {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "HH:mm"
            return dateFormatter.date(from: self)
        }
    
    }
    

    Uses example:

    override func viewDidLoad() {
            let dateString = "11:32"
            if let date = dateString.date { //This will return Date object
                debugPrint(date)
            }
    
            let invalidDateString = "XYZ:ABC"
            if let invalidDate = invalidDateString.date { //This will return nil as date string is invalid
                debugPrint(invalidDate)
            }
        }