Home > Net >  DateIntervalFormatter: string of format "m:ss"
DateIntervalFormatter: string of format "m:ss"

Time:11-19

I'd like to get a string of format "m:ss" out of two dates. E.g.: "0:27" for 27 seconds difference and "1:30" for 90 seconds difference between dates.

Here's the code I'm using:

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.

But I'm getting just two dates printed out with a dash. How can I actually make the DateIntervalFormatter to calculate the difference as I want?

The code is almost 1:1 sample from the Apple documentation but with the custom dateTemplate: https://developer.apple.com/documentation/foundation/dateintervalformatter

CodePudding user response:

I created this solution which doesn't involve the DateIntervalFormatter:

import Foundation

let minutes = 2
let seconds = 9

let formatted = String(format: "d:d", minutes, seconds)
print(formatted) // 2:09

Looks like what DateIntervalFormatter does is just applying a standard Date->String conversion to both of the dates and adds a dash between them.

CodePudding user response:

It seems that you actually want 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)

to remove the leading zero if the minutes are < 10 you could use Regular Expression

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