問題は、名前にもかかわらず、differenceDate
は、日付ではありません!これはちょうど時間間隔 - 秒の抽象的な秒です。時間と分と秒で表現したい場合は、60で割って残りの部分を取ってください。しかし、それらが実際の時間と分と秒ではないことに注意してください。
例:
// make two dates, get the difference
let greg = Calendar(identifier: .gregorian)
let dc = DateComponents(calendar: greg,
year: 1954, month: 8, day: 10, hour: 3, minute: 0, second: 0)
let d1 = greg.date(from: dc)!
let d2 = Date()
let diff = d2.timeIntervalSince(d1)
// calculate hours, minutes, and seconds
var min = diff/60
let sec = diff.truncatingRemainder(dividingBy: 60)
let hr = min/60
min = min.truncatingRemainder(dividingBy: 60)
// format the output as a string
let nf = NumberFormatter()
nf.roundingMode = .floor
nf.minimumIntegerDigits = 2
let hrs = nf.string(from: hr as NSNumber)
let mins = nf.string(from: min as NSNumber)
nf.maximumFractionDigits = 3
let secs = nf.string(from: sec as NSNumber)
print(hrs! + ":" + mins! + ":" + secs!) // 545169:33:18.841
これは、あなたの希望のフォーマットと、あなたのミリ秒を与えます。 Robによって提案されているように、DateComponentsFormatterでも同じことができますが、計算結果はまったく同じになります。
日はフードの下の秒数で使用していたことがわかりました。しかし秒数(ミリ秒)は日付ではありません!ここでは、DateFormatterの使用は完全に不適切です。 – matt
私のビジネスルールではミリ秒を使用する必要があるので、私はそれを使用しなければなりません。 Double(currentTimeInMilisecondsは実際にミリ秒を保持する変数に移動しますが、より説明しやすくするために変更しました) – user1079052
これはミリ秒とは関係ありません。日付形式ではありませんA.日付。 – matt