Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateComponentsFormatter returns wrong number of unit count

I've faced issue, when DateComponentsFormatter returns unexpected number of units. Does anyone faced same issue?

import Foundation

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full;
formatter.maximumUnitCount = 1;

let date = Date(timeIntervalSinceNow: -14.7 * 24 * 60 * 60)
let dateString = formatter.string(from: date, to: Date()) // 2 weeks 1 day

I expect to receive "2 weeks", but have "2 weeks 1 day".

like image 504
Timur Bernikovich Avatar asked Dec 16 '16 14:12

Timur Bernikovich


1 Answers

I solved the issue by checking for the comma separator and using it to substring the DateFormatters output, PlayGround example in Swift 3

// Test date
var df = DateFormatter()
df.dateFormat = "dd.MM.yyyy HH:mm:ss"
df.timeZone = TimeZone(secondsFromGMT: 0)
let fromDate = df.date(from: "01.01.2000 00:00:00")
var timeDifference = Date().timeIntervalSince(fromDate!)

// Setup formatter
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.includesApproximationPhrase = false
formatter.zeroFormattingBehavior = .dropAll
formatter.maximumUnitCount = 1
formatter.allowsFractionalUnits = false

// Use the configured formatter to generate the string.
var outputString = formatter.string(from: timeDifference) ?? ""

// Remove 2nd unit if exists
let commaIndex = outputString.characters.index(of: ",") ?? outputString.endIndex
outputString = outputString.substring(to: commaIndex)

// Result
print(outputString)
like image 106
Mknsri Avatar answered Sep 21 '22 13:09

Mknsri