Search code examples
iosswiftnsdatensregularexpression

How to check for valid time format?


I am trying to check if a string variable conforms to either hh:mm AM or hh:mm PM twelve hour time format. Where hh represents hours, mm represents minutes and AM or PM represents morning or evening. I have a CSV file where each line contains a time in 12-hour format for instance 01:00 PM or 12:00 AM. I am extracting each line and checking if it conforms to the desired format.


Solution

  • Just pass the string to a date formatter with the required format. If it returns a Date object, then the string contains valid date.

    func getDate(from string: String) -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd h:mm a"
        return dateFormatter.date(from: string)
    }
    
    if let date = getDate(from: "2019-02-14 9:28 PM") {
        print(date)
    }
    

    Check NSDateFormatter.com for reference.