简体   繁体   中英

Swfit- Check whether current time is between two time string

How to check if the current time is between two-time strings in the following format. HH:MM AM/PM say if

startTime = "10:30 AM" 
endTime = "06:30 PM"

how to check if currentTime() value is in between start and end times?

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

You can use Swift's Dateformatter() to encode and compare dates:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
dateFormatter.defaultDate = Calendar.current.startOfDay(for: Date())
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"

let startTimeFormatted = dateFormatter.today.date(from: startTime)
let endTimeFormatted = dateFormatter.today.date(from: endTime)

//Now you can compare the two, e.g.

if startTimeFormatted > currentDate() && currentDate() < endTimeFormatted{
    return true
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM