DateIntervalFormatter:格式字符串 "m:ss"
DateIntervalFormatter: string of format "m:ss"
我想从两个日期中获取格式为“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
我创建了这个不涉及 DateIntervalFormatter 的解决方案:
import Foundation
let minutes = 2
let seconds = 9
let formatted = String(format: "%01d:%02d", minutes, seconds)
print(formatted) // 2:09
看起来 DateIntervalFormatter 所做的只是对两个日期应用标准的 Date->String 转换并在它们之间添加破折号。
看来你真的想要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: "", options: .regularExpression))
我想从两个日期中获取格式为“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
我创建了这个不涉及 DateIntervalFormatter 的解决方案:
import Foundation
let minutes = 2
let seconds = 9
let formatted = String(format: "%01d:%02d", minutes, seconds)
print(formatted) // 2:09
看起来 DateIntervalFormatter 所做的只是对两个日期应用标准的 Date->String 转换并在它们之间添加破折号。
看来你真的想要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: "", options: .regularExpression))