Search code examples
swiftdatetimetimestampnsdate

Swift 5: Calculate current time is between 2 times


I am not good at Swift so I would like to know how to calculate the current time is between two times.

I got the following response from the backend. {"workHours":"M-F 9:00 - 18:00"}

From the above string, how to write a class/struct(or another best way) to validate today's current time is in the described time range("M-F 9:00 - 18:00")?

public final class DateValidator {
    let startTime: Date?
    let endTime: Date?
    
    func isInRange() -> Bool {
        // write modules here
        // How to validate
    }
    
    public init(dateString: String) {
        // dateString should be "M-F 9:00 - 18:00"
        // Extract startTime and endTime from dateString
    }
}

Solution

  • Set up the DateComponentsFormatter

    let dcf = DateComponentsFormatter()
    dcf.allowedUnits = [.day, .hour, .minute, .second]
    dcf.unitsStyle = .full
    

    Set up ordinary date formatter

    let df = ISO8601DateFormatter()
    df.formatOptions = [.withFullDate, .withDashSeparatorInDate]
    

    Perform formatting

    if let future = df.date(from: "2019-04-29"), let diff = dcf.string(from: Date(), to: future) {
        print(diff)
    }
    

    Output is

    3 days, 6 hours, 9 minutes, 9 seconds