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

如何用DateIntervalFormatter输出两个日期的m:ss格式时间差

你使用的DateIntervalFormatter是用于展示两个时间点组成的区间范围的格式化工具,默认输出就是「开始时间 - 结束时间」的格式,本身不具备计算两个日期时间差、输出间隔时长的能力,所以你得到的结果符合该类的设计定位,只是选型不符合你的需求。


你可以换用DateComponentsFormatter实现需求,示例代码如下:

import Foundation

// 示例日期
let startDate = Date()
let endDate = Date(timeInterval: 90, since: startDate) // 间隔90秒用于测试

// 计算时间差
let timeGap = endDate.timeIntervalSince(startDate)

// 初始化并配置格式化器
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second] // 只保留分钟、秒两个单位
formatter.unitsStyle = .positional // 使用冒号分隔的位置格式
formatter.zeroFormattingBehavior = .pad // 给不足两位的秒数补前导零,分钟保留原值不补前导零

// 生成结果
if let output = formatter.string(from: timeGap) {
    print(output) // 90秒输出1:30,27秒输出0:27,符合需求
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:15:06