如何格式化时间并检查Swift

时间:2016-03-18 17:43:32

标签: swift nsdate nsdateformatter

我一直在玩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)

1 个答案:

答案 0 :(得分: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")
}