如何检查有效的时间格式?

How to check for valid time format?

我正在尝试检查字符串变量是否符合 hh:mm AM 或 hh:mm PM 十二小时时间格式。其中 hh 代表小时,mm 代表分钟,AM 或 PM 代表早上或晚上。我有一个 CSV 文件,其中每一行都包含一个 12 小时格式的时间,例如 01:00 PM 或 12:00 AM。我正在提取每一行并检查它是否符合所需的格式。

只需将字符串传递给具有所需格式的日期格式化程序。如果它 returns 一个 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)
}

检查 NSDateFormatter.com 以供参考。

我宁愿使用 DateFormatter,但如果您坚持使用 RegEx,请试试这个:

let dateString = "21:23 PM"
if let thisMatches = dateString.range(of: "^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm)$", options: .regularExpression) {
    Swift.print("this is a time")
} else {
    Swift.print("this is not the time")
}

使用此代码获取指定时间是否有效。

案例一:

let myTime = checkTimeIsValid(from: "01:28 AM")
print("Time Is Valid:", myTime) //Time Is Valid: true

案例2:

let myTime = checkTimeIsValid(from: "21:28 AM")
print("Time Is Valid:", myTime) //Time Is Valid: false

函数:

func checkTimeIsValid(from string: String) -> Bool {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "hh:mm a"
    if (dateFormatter.date(from: string) != nil) {
        return true
    }else{
        return false
    }
}