You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 4中日期日比较问题:如何判断日期是否为过去日期

Filtering Past Dates in Swift

I see you're trying to filter out dates that are in the past from your selected calendar dates — let's fix up that code to get it working correctly!

Issues with Your Current Code

Your current approach has a couple of key problems:

  • When you call calendar.dateComponents([], from: Date()), you're passing an empty array of components. This means no date parts (year, month, day) are extracted, so calendar.date(from: components) will return nil. Force-unwrapping that with ! will cause a crash.
  • You're attempting to compare dates without normalizing the time component, which can lead to incorrect results (e.g., a date that's today but earlier in the day might be incorrectly marked as past).

Corrected Solution

To properly filter past dates, we need to:

  1. Get the current date with the time component stripped off (so we're only comparing year/month/day).
  2. Filter your selected dates to find those that are strictly before this normalized current date.

Here's the revised code:

let calendar = NSCalendar.current
// Extract year, month, day components from the current date
let todayComponents = calendar.dateComponents([.year, .month, .day], from: Date())
// Create a date representing the start of today (no time component)
guard let startOfToday = calendar.date(from: todayComponents) else {
    // Handle the case where we couldn't create the date (unlikely, but safe to handle)
    pastDates = []
    return
}
// Filter selected dates to find those before the start of today
let pastDates = self.calendar.selectedDates.filter { $0 < startOfToday }

Explanation

  • By specifying [.year, .month, .day] in dateComponents, we extract only the date parts we care about, which allows us to create a date representing the very start of today (midnight).
  • Using guard let instead of force-unwrapping (!) makes the code safer, avoiding crashes if for some reason the date can't be created.
  • Comparing each selected date to startOfToday ensures that any date before today (regardless of time) is correctly identified as past.

内容的提问来源于stack exchange,提问作者Rupesh Baldania

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:15:19