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

Swift中如何拆分包含今日与明日时间戳的整数数组

如何将时间戳数组拆分为今日、明日子数组

嗨,这个问题的核心是用日期边界精准区分时间戳的归属,结合你已经写好的Date扩展,我们可以借助Calendar来处理时区和夏令时的坑,不用手动算秒数踩雷,下面是具体实现方案:

步骤1:补充时间戳的日期判断工具方法

我们先给Int扩展两个判断方法,用来快速识别时间戳属于今日还是明日:

extension Int {
    // 你已有的时间戳转时分字符串方法
    func getTimetringFromINT() -> String {
        let date = Date(timeIntervalSince1970: TimeInterval(self))
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale(identifier: "id")
        dateFormatter.dateFormat = "HH:mm"
        return dateFormatter.string(from: date)
    }
    
    // 判断当前时间戳是否属于今日
    func isToday() -> Bool {
        let currentDate = Date(timeIntervalSince1970: TimeInterval(self))
        return Calendar.current.isDateInToday(currentDate)
    }
    
    // 判断当前时间戳是否属于明日
    func isTomorrow() -> Bool {
        let currentDate = Date(timeIntervalSince1970: TimeInterval(self))
        return Calendar.current.isDateInTomorrow(currentDate)
    }
}

步骤2:拆分数组的核心实现

有了上面的判断方法,拆分数组就变得非常简单,直接用filter方法分别筛选即可:

let dateCollection = [ 1633722900, 1633730500, 1633754910, 1633758913, 1633820400, 1633824000, 1633827600, 1633831200, 1633834800, 1633838400, 1633842000 ]

// 筛选今日的时间戳
let today = dateCollection.filter { $0.isToday() }
// 筛选明日的时间戳
let tomorrow = dateCollection.filter { $0.isTomorrow() }

// 打印验证结果
print("今日数组:\(today)")
print("明日数组:\(tomorrow)")

为什么用Calendar而不是手动算秒数?

直接给时间戳加86400(一天的秒数)看起来省事,但会遇到夏令时切换的问题(比如部分地区一天是23或25小时),用Calendar提供的isDateInToday()和isDateInTomorrow()会自动处理时区、夏令时的差异,结果更准确可靠。

测试你的示例数组

运行上述代码后,得到的结果和你期望的完全一致:

  • today数组:[1633722900, 1633730500, 1633754910, 1633758913]
  • tomorrow数组:[1633820400, 1633824000, 1633827600, 1633831200, 1633834800, 1633838400, 1633842000]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 17:44:07