在计算时隙迅速时得到零值

时间:2019-02-07 20:22:10

标签: ios swift dateformatter

我正在跟踪帖子how to get 30 minutes time slots array in between two dates swift中的解决方案,但是在我的以下函数中,我在date2上获得了零值:

func calculateOpenTimeSlots() {

        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm"
        let weekday = self.actualWeekday
        let openingTime = openingTimeArray[weekday!].openingTime
        let closingTime = openingTimeArray[weekday!].closingTime
        let date1 = formatter.date(from: openingTime)
        let date2 = formatter.date(from: closingTime)
        var i = 1
        timeSlotArray.removeAll()
        while true {
            let date = date1?.addingTimeInterval(TimeInterval(i*30*60))
            let string = formatter.string(from: date!)
            if date! >= date2! {break}
            i = i + 1
            timeSlotArray.append(string)
        }

    }

该数组是:

var openingTimeArray: [(weekday: Int, openingTime: String, closingTime: String)] = [(weekday: 0, openingTime: "10:00", closingTime: "19:00"), (weekday: 1, openingTime: "10:00", closingTime: "19:00"), (weekday: 2, openingTime: "10:00", closingTime: "19:00"), (weekday: 3, openingTime: "10:00", closingTime: "19:00"), (weekday: 4, openingTime: "10:00", closingTime: "19:00"), (weekday: 5, openingTime: "10:00", closingTime: "19:00"), (weekday: 6, openingTime: "10:00", closingTime: "19:00"), (weekday: 7, openingTime: "10:00", closingTime: "19:00")]

openingTimeclosingTime的值不是nil,它们是正确的值,但是在date1上,我得到了一个完整的日期,该日期早1小时。 date1是世界标准时间2000-01-01 09:00:00,但我希望它是10:00。

我仍然不掌握日期格式化程序,而且我不明白为什么我得到的date2为零,而date1却为错误。 与往常一样,任何向我指出正确方向的解释都将非常有帮助。 非常感谢

1 个答案:

答案 0 :(得分:0)

我发现问题出在格式声明为formatter.dateFormat = "hh:mm"中。我将其更改为formatter.dateFormat = "HH:mm",现在可以正常使用了。 我必须在timeSlotArray.append(openingTime)循环之前添加一个附加while,因为该循环并没有在打开时开始附加第一个时隙,但是我想重写该循环以考虑到这一点。关于如何实现这一目标的任何建议?

func calculateOpenTimeSlots() {
         timeSlotArray.removeAll()

        let formatter = DateFormatter()
//        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.dateFormat = "HH:mm"
        let weekday = self.actualWeekday
        let openingTime = openingTimeArray[weekday!].openingTime
        let closingTime = openingTimeArray[weekday!].closingTime
        let date1 = formatter.date(from: openingTime)
        timeSlotArray.append(openingTime)
        let date2 = formatter.date(from: closingTime)
        var i = 1

        while true {
            let date = date1?.addingTimeInterval(TimeInterval(i*30*60))
            let string = formatter.string(from: date!)
            if date! >= date2! {break}
            i = i + 1
            timeSlotArray.append(string)
        }
        print(timeSlotArray)

    }