Swift - 用日期和比较替换INT

时间:2018-04-08 07:58:42

标签: ios iphone swift

我有这段代码:

let miesiacOd : 2017
let rokOd : Int = 10
let dzienOd : Int = 1
let dataOd = String(format: "%02d-%02d-%02d", rokOd, miesiacOd, dzienOd)

let miesiacDo : Int = 2018
let rokDo : Int = 10
let dzienDo : Int = 1
let dataDo = String(format: "%02d-%02d-%02d", rokDo, miesiacDo, dzienDo)


let dateFormatter2 = DateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd"

我正在尝试比较它,但我有错误。将变量转换为日期时:

let dataDo2 = dateFormatter2.date(from: dataDo)
let dataOd2 = dateFormatter2.date(from: dataOd)

我有结果的日期和时间。例如:2017-10-01 +000 为什么会发生这种情况以及如何解决?

最后,我想检查当前日期是否在上述日期之内。

我试图这样做:

let sprawdzamDostepnoscDat = Date().isBetweeen(date: dataOd2!, andDate: dataDo2!)


extension Date {

    func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
        return date1.timeIntervalSince1970 < self.timeIntervalSince1970 && date2.timeIntervalSince1970 > self.timeIntervalSince1970
    }

}

这个解决方案可以吗?

1 个答案:

答案 0 :(得分:0)

您不需要格式化程序(字符串解析器)来创建Date

var dateFromComponents = DateComponents()
dateFromComponents.year = 2017
dateFromComponents.month = 10
dateFromComponents.day = 1
let dateFrom = Calendar.current.date(from: dateFromComponents)

var dateToComponents = DateComponents()
dateToComponents.year = 2018
dateToComponents.month = 10
dateToComponents.day = 1
let dateTo = Calendar.current.date(from: dateToComponents)

另请注意,Date已经具有可比性,因此您的inBetween功能可以只是:

extension Date {
    func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
       return date1 <= self && self <= date2
    }
}

但是,如果您想忽略时间并仅比较日期,则应使用:

extension Date {
    func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
        return Calendar.current.compare(date1, to: self, toGranularity: .day) != .orderedDescending
        && Calendar.current.compare(self, to: date2, toGranularity: .day) != .orderedDescending
    }
}