gpt4 book ai didi

ios - Swift - 用日期替换 INT 并进行比较

转载 作者:行者123 更新时间:2023-11-30 11:36:28 25 4
gpt4 key购买 nike

我有这个代码:

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
}

}

这个解决方案可以吗?

最佳答案

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

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
}
}

关于ios - Swift - 用日期替换 INT 并进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49715726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com