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

Swift中时/分/秒转整数:将7时30分5秒转为整数

在Swift中把时分秒转换为整数(总秒数)

没问题,这事儿在Swift里实现起来超简单——咱们要把7小时30分钟5秒转换成整数,最常用的方式是转成总秒数(如果需要转成总分钟数也可以轻松调整逻辑)。

核心思路

时间单位的换算关系很明确:

  • 1小时 = 3600秒
  • 1分钟 = 60秒

所以总秒数的计算公式就是:小时数 × 3600 + 分钟数 × 60 + 秒数

直接实现代码

如果只是单次计算,直接写表达式就行:

let hours = 7
let minutes = 30
let seconds = 5

let totalSeconds = hours * 3600 + minutes * 60 + seconds
print(totalSeconds) // 输出结果:27005

封装成复用函数

要是你需要多次进行这种转换,把逻辑封装成函数会更方便:

func convertTimeToTotalSeconds(hours: Int, minutes: Int, seconds: Int) -> Int {
    return hours * 3600 + minutes * 60 + seconds
}

// 调用示例
let total = convertTimeToTotalSeconds(hours: 7, minutes: 30, seconds: 5)
print(total) // 同样输出:27005

额外说明

如果你的需求是转换成总分钟数(取整),可以用这个逻辑:

let totalMinutes = hours * 60 + minutes + seconds / 60
print(totalMinutes) // 输出:450(因为5秒不足1分钟,取整后忽略)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:32:37