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

Swift中格式化日期时间:当日仅显示时间的实现方案

实现当日仅显示时间的日期格式化方案

你可以利用Calendar的isDateInToday(_:)方法来判断日期是否为当日,这个方法由系统封装,会自动处理时区、日历规则等细节,完全不需要手动计算当日日期。

修改后的代码如下:

let dateFormatter = DateFormatter()
dateFormatter.timeStyle = .short
dateFormatter.locale = .current

// 直接用系统方法判断是否为当日
if Calendar.current.isDateInToday(date) {
    dateFormatter.dateStyle = .none
} else {
    dateFormatter.dateStyle = .short
}

lblDateTime.text = dateFormatter.string(from: date)

说明

  • Calendar.current.isDateInToday(date)会自动匹配当前设备的时区和日历设置,比自己获取当前日期再做比较更准确,能避免凌晨时分的日期边界问题。
  • 这种方式完全省去了手动计算当日起始/结束时间、处理时区偏移等繁琐步骤,代码简洁且可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 12:59:14