如何在Swift中格式化时间并检查“工作时间”

问题描述 投票:0回答:1

我一直在使用NSDate(),但是遇到了麻烦,需要帮助。我需要检查工作时间,如果用户在开放时间使用应用程序,则会出现一些绿点。

我使用Firebase和工作时间的数据是:

main 
---> key
     ----> working hours
           -------------->
                            Mon: 12:00-18:00
                            Tue: 11:30-21:00
                            etc.

我明白了。抢一周中的一天。在Firebase中抓取正确的行。抓住用户当前时间,看看是否给定范围。我仍然是初学者,但我想学习如何做到这一点。

有人可以指导我一点吗?这是我现在只有的代码:

// Check current time
        let userTime = NSDate()
        let formatter = NSDateFormatter();
        formatter.dateFormat = "HH:mm"
        let now = formatter.stringFromDate(userTime)
        print(now)
swift nsdate nsdateformatter
1个回答
0
投票

因为没有问题应该没有答案;)

由于您的模式是稳定的,因此可以将正则表达式与命名组一起使用。将正则表达式模式保留在函数之外。

let regex = try! NSRegularExpression(pattern: "(?<day>\\w{3}):\\s(?<openHour>\\d{2}):(?<openMin>\\d{2})-(?<closeHour>\\d{2}):(?<closeMin>\\d{2})",
                                     options: .caseInsensitive)

这里是一个需要输入“星期一:12:00-18:00”的函数,您可以根据正确的日期选择现在的日期,或者也可以将日期检查移入该函数。

func isOfficeOpenNow(input: String) -> Bool {

    let range = NSRange(location: 0, length: input.utf8.count)

    guard let match = regex.firstMatch(in: input, options: [], range: range) else {
        assert(false, "Epic Fail!")
    }

    guard let dayRange = Range(match.range(withName: "day"), in: input),
        let openHourRange = Range(match.range(withName: "openHour"), in: input),
        let openMinRange = Range(match.range(withName: "openMin"), in: input),
        let closeHourRange = Range(match.range(withName: "closeHour"), in: input),
        let closeMinRange = Range(match.range(withName: "closeMin"), in: input) else {
        assert(false, "Did not find the named groups")
    }

    let day = String(input[dayRange])
    guard let openHour = Int(input[openHourRange]),
            let openMin = Int(input[openMinRange]),
            let closeHour = Int(input[closeHourRange]),
            let closeMin = Int(input[closeMinRange]) else {
        assert(false, "Failed to convert to ints")
    }

    print("day: \(day) Opens at: \(openHour):\(openMin) and closes at \(closeHour):\(closeMin)")

    // Lets check if its now open (not checking the day....sorry)
    let tz = NSTimeZone.default
    let now = NSCalendar.current.dateComponents(in: tz, from: Date())

    guard let hour = now.hour,
        let minute = now.minute else  {
            assert(false, "this should never happen")
    }

    let rightNowInMinutes = hour * 60 + minute
    let opensAt = openHour * 60 + openMin
    let closesAt = closeHour * 60 + closeMin

    assert(opensAt < closesAt, "Opening after closing does not make sense")

    return rightNowInMinutes > opensAt &&
        rightNowInMinutes < closesAt
}

这里是使用方法

if isOfficeOpenNow(input: "Mon: 12:00-18:00") {
    print("Store open")
} else {
    print("Store closed")
}
© www.soinside.com 2019 - 2024. All rights reserved.