如何在TableView中按日期筛选数组?附myAlert示例JSON数据
Hey there! Let's work through how to implement date-based filtering for your TableView using that myAlert JSON data you shared. I'll walk you through a complete Swift implementation (since it's the most common for iOS TableViews these days), and you can adapt it to your needs easily.
First, let's turn that raw JSON into a Swift model so we can work with it more safely and cleanly. We'll use Codable to handle the JSON parsing:
struct AlertModel: Codable { let usaTime: String let vsTitle: String let vsStartTime: String let vsEndTime: String let vsStatus: String let vsAddTime: String // Map the snake_case JSON keys to camelCase Swift properties enum CodingKeys: String, CodingKey { case usaTime = "usa_time" case vsTitle = "vs_title" case vsStartTime = "vs_start_time" case vsEndTime = "vs_end_time" case vsStatus = "vs_status" case vsAddTime = "vs_add_time" } }
Date handling can be tricky, so let's make a reusable formatter to parse and format the dates consistently. We'll add an extension to DateFormatter:
extension DateFormatter { static let alertDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Matches your JSON date format formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) // Adjust this if you need to account for time zones return formatter }() // Helper to extract just the date part (no time) as a string static func getDateOnlyString(from dateString: String) -> String? { guard let fullDate = alertDateFormatter.date(from: dateString) else { return nil } let dateOnlyFormatter = DateFormatter() dateOnlyFormatter.dateFormat = "yyyy-MM-dd" return dateOnlyFormatter.string(from: fullDate) } }
Let's say you want to filter alerts where the vs_start_time falls on a specific date (like "2018-04-29"). Here's how you can do that:
// Your original array of alerts (after parsing the JSON) var originalAlerts: [AlertModel] = [] // Your filtered array to use as TableView data source var filteredAlerts: [AlertModel] = [] // Example target date (you could get this from a date picker, user input, etc.) let targetDate = "2018-04-29" // Perform the filter filteredAlerts = originalAlerts.filter { alert in // Get the date-only string from the alert's start time guard let alertDate = DateFormatter.getDateOnlyString(from: alert.vsStartTime) else { return false // Skip alerts with invalid date strings } // Match against the target date return alertDate == targetDate }
If you want to filter by a different date field (like vs_add_time), just swap out alert.vsStartTime with alert.vsAddTime in the code above.
Once you have the filtered array, update your TableView's data source and refresh it:
// Assign the filtered array to your TableView data source tableViewDataSource = filteredAlerts // Refresh the TableView to show the filtered results yourTableView.reloadData()
If you want users to pick a date via a UIDatePicker to trigger filtering, add this handler:
@objc func datePickerDidChange(_ sender: UIDatePicker) { let dateOnlyFormatter = DateFormatter() dateOnlyFormatter.dateFormat = "yyyy-MM-dd" let selectedDateString = dateOnlyFormatter.string(from: sender.date) // Re-filter the alerts filteredAlerts = originalAlerts.filter { alert in guard let alertDate = DateFormatter.getDateOnlyString(from: alert.vsStartTime) else { return false } return alertDate == selectedDateString } // Update the TableView tableViewDataSource = filteredAlerts yourTableView.reloadData() }
- Date Range Filtering: If you need to filter alerts between two dates (instead of a single date), compare
Dateobjects directly instead of strings:let startDate = Date() // Your start date let endDate = Date().addingTimeInterval(86400) // 1 day after start date filteredAlerts = originalAlerts.filter { alert in guard let startTime = DateFormatter.alertDateFormatter.date(from: alert.vsStartTime) else { return false } return startTime >= startDate && startTime <= endDate } - Error Handling: Make sure to handle cases where date parsing fails (like invalid date strings in the JSON) to avoid crashes.
内容的提问来源于stack exchange,提问作者Palak Patel

