[Solved] Swfit- Check whether current time is between two time string


You can set the date formatter defaultDate for today, parse the date strings, create a DateInterval with the start and end date and check if it contains now Date():

extension Formatter {
    static let today: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.locale = .init(identifier: "en_US_POSIX")
        dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
        dateFormatter.dateFormat = "hh:mm a"
        return dateFormatter
        
    }()
}

func checkIfCurrentTimeIsBetween(startTime: String, endTime: String) -> Bool {
    guard let start = Formatter.today.date(from: startTime),
          let end = Formatter.today.date(from: endTime) else {
        return false
    }
    return DateInterval(start: start, end: end).contains(Date())
}

let startTime = "10:30 AM"
let endTime = "06:30 PM"
checkIfCurrentTimeIsBetween(startTime: startTime, endTime: endTime)   // true

3

solved Swfit- Check whether current time is between two time string