swift - 日期间隔格式化程序 : string of format "m:ss"

标签 swift date foundation dateformatter dateinterval

我想从两个日期中获取格式为“m:ss”的字符串。 例如:“0:27”表示日期之间相差 27 秒,“1:30”表示日期之间相差 90 秒。

这是我正在使用的代码:

import Foundation
let formatter = DateIntervalFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .none
formatter.dateTemplate = "m:ss"

let startDate = Date()
let endDate = Date(timeInterval: 1, since: startDate)

let outputString = formatter.string(from: startDate, to: endDate)
print(outputString) //16:12 – 16:13 ???
// This is correct, but it doesn't actually calculate the interval.

但是我只得到了两个带有破折号的日期。 我怎样才能真正让 DateIntervalFormatter 计算出我想要的差异?

该代码几乎是 Apple 文档中的 1:1 示例,但使用了自定义 dateTemplate:https://developer.apple.com/documentation/foundation/dateintervalformatter

最佳答案

看来您确实想要DateComponentsFormatter

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
let startDate = Date()
let endDate = Date(timeInterval: 129, since: startDate)

let outputString = formatter.string(from: startDate, to: endDate)!
print(outputString)

如果分钟数 < 10,则可以使用正则表达式删除前导零

print(outputString.replacingOccurrences(of: "^0(\\d)", with: "$1", options: .regularExpression))

关于swift - 日期间隔格式化程序 : string of format "m:ss",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70023299/

相关文章:

ios - fatal error : index out of range tableview with two sections

java - 保存到数据库时日期以不同的格式保存

iphone - iOS:NSSocketPort,你在哪里?

objective-c - 类型类数组的问题

c++ - 在导入 Foundation 的 objective-c 文件上运行 Clang-query

swift - 将带有参数的闭包传递给 SwiftUI View

ios - 为什么 UIView 的 CALayer.speed 为零会阻止 UIAlertController 的按钮工作?

swift - 匹配CNcontact和Digits Find Friends Swift 3

c# - 将日期转换为仅 yyyy-mm-dd

php - MySQL 填充空日期