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

SwiftUI中如何按月份过滤结构体数组?日期为时间戳格式

筛选结构体数组中特定月份的条目(时间戳格式日期)

核心思路

把时间戳转换为Date对象,通过Calendar提取日期的月份信息,再对数组进行筛选,保留符合目标月份的元素。如果需要精准筛选(避免跨年份的同月份数据),可以同时匹配年份和月份。

代码实现

基于你提供的代码,我们可以在Test类中添加筛选方法:

import SwiftUI

struct TestStruct {
    var food: String
    var date: Double
}

class Test: ObservableObject {
    let food1 = TestStruct(food: "Hamburger", date: 1641058794)
    let food2 = TestStruct(food: "HotDog", date: 1651426794)
    let food3 = TestStruct(food: "icecream", date: 1652204394)
    let foodForYear: [TestStruct] = [food1, food2, food3]
    
    // 筛选特定月份的条目(不限制年份)
    func filterByMonth(targetMonth: Int) -> [TestStruct] {
        let calendar = Calendar.current
        return foodForYear.filter { item in
            let date = Date(timeIntervalSince1970: item.date)
            let month = calendar.component(.month, from: date)
            return month == targetMonth
        }
    }
    
    // 筛选特定年份+月份的条目(精准匹配)
    func filterByMonthAndYear(targetMonth: Int, targetYear: Int) -> [TestStruct] {
        let calendar = Calendar.current
        return foodForYear.filter { item in
            let date = Date(timeIntervalSince1970: item.date)
            let components = calendar.dateComponents([.year, .month], from: date)
            return components.year == targetYear && components.month == targetMonth
        }
    }
}

使用示例

在SwiftUI视图中调用筛选方法,展示结果:

struct ContentView: View {
    @StateObject var testModel = Test()
    
    var body: some View {
        VStack(spacing: 20) {
            Text("1月的食物")
                .font(.headline)
            ForEach(testModel.filterByMonth(targetMonth: 1), id: \.food) { item in
                Text(item.food)
            }
            
            Text("2022年5月的食物")
                .font(.headline)
            ForEach(testModel.filterByMonthAndYear(targetMonth: 5, targetYear: 2022), id: \.food) { item in
                Text(item.food)
            }
        }
        .padding()
    }
}

结果说明

你提供的三个时间戳对应的日期:

  • 1641058794 → 2022年1月,筛选1月会得到Hamburger
  • 1651426794 → 2022年5月
  • 1652204394 → 2022年5月
    所以筛选2022年5月会得到HotDog和icecream

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:10:31