我如何檢查任何日期是否在兩個日期之間。例如,我想檢查當前日期是否在 12 月 15 日到 1 月 15 日之間。
這可以是任何一年,所以我當前的日期可能是 2023 年 12 月 15 日,它應該回傳 true。如果它的 12 月 14 日或任何一年的 1 月 16 日,它應該回傳 false。12 月 31 日應該回傳 true。
這是我嘗試過的
let now = currentDateProvider()
dateFormatter.dateFormat = "yyyy-MM-dd"
let year = Calendar.current.component(.year, from: now)
guard let start = dateFormatter.date(from: "\(year)-01-01"),
let end = dateFormatter.date(from: "\(year)-01-07") else {
return false
}
if start <= now && now <= end {
return true
}
guard let start = dateFormatter.date(from: "\(year)-12-01"),
let end = dateFormatter.date(from: "\(year)-12-31") else {
return false
}
let value = start <= now && now <= end
return value
但它接縫有點錯誤,因為如果我的時區是 uct 2 那么結束日期給我 12 月 30 日 22:00:00 因為 uct 2 是 12 月 31 日 00:00 - 2 小時它給你 12 月 30 日而不是 31 日。
理想情況下,我希望不必單獨檢查日期,只需在 12 月 15 日至 1 月 15 日之間進行一次包含檢查,而不是檢查 12 月 15 日至 12 月 31 日和 1 月 1 日至 1 月 7 日。
uj5u.com熱心網友回復:
您不能忽略年份,尤其是當年份在間隔內時。由于實際上涉及當前日期,因此您要檢查日期是否在當年的 12 月和明年的1 月之內
我的建議是從當前日期獲取年份組件,然后通過將月份設定為 12 并將天設定為 15 來構建開始日期,并通過在指向下一個 1 月 16 日的開始日期添加一天和一個月來構建結束日期年。
let currentDate = Date.now
let year = Calendar.current.component(.year, from: currentDate)
let startComponents = DateComponents(year: year, month: 12, day: 15)
let startDate = Calendar.current.date(from: startComponents)!
let endDate = Calendar.current.date(byAdding: DateComponents(month: 1, day: 1), to: startDate)!
if currentDate >= startDate && currentDate < endDate {
print("isValid")
}
uj5u.com熱心網友回復:
我將獲取日期的月份和日期的日期組件,并對值進行簡單比較
let components = Calendar.current.dateComponents([.month, .day], from: date)
let inPeriod = (components.month! == 12 && components.day! >= 15) || (components.month! == 1 && components.day! <= 15)
簡單的測驗用例
for _ in 1...34 {
let components = Calendar.current.dateComponents([.month, .day], from: testDate)
print(testDate, (components.month! == 12 && components.day! >= 15) || (components.month! == 1 && components.day! <= 15))
testDate = Calendar.current.date(byAdding: .day, value: 1, to: testDate)!
}
uj5u.com熱心網友回復:
Date 符合 Comparable 協議,因此您可以:
var initialDate = Date(timeIntervalSince1970: 10000)
var finalDate = Date(timeIntervalSinceNow: 10000)
var todayDate = Date()
todayDate > initialDate
todayDate < finalDate
在 Ifs 或任何你喜歡的地方使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529797.html
標籤:IOS迅速代码
上一篇:SQL格式字串
