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, socalendar.date(from: components)will returnnil. 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:
- Get the current date with the time component stripped off (so we're only comparing year/month/day).
- 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]indateComponents, 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 letinstead of force-unwrapping (!) makes the code safer, avoiding crashes if for some reason the date can't be created. - Comparing each selected date to
startOfTodayensures that any date before today (regardless of time) is correctly identified as past.
内容的提问来源于stack exchange,提问作者Rupesh Baldania
相关产品推荐
相关产品推荐

