swifttimensdateformatternsdatecomponentsnsdatecomponentsformatter

DateComponentsFormatter and .nanosecond


So, I'm using a DateComponentsFormatter in a situation where I need to format only the nanoseconds of a given TimeInterval. The problem is that it just does not work as intended, or I'm confusing something here that I'm not aware of.

Here are 3 quick tests to illustrate what I'm saying.

1st Scenario

let fooFormatter = DateComponentsFormatter()

fooFormatter.allowedUnits = [.second, .nanosecond]
fooFormatter.unitsStyle = .full
fooFormatter.collapsesLargestUnit = true
fooFormatter.allowsFractionalUnits = true

print(fooFormatter.string(from: 42.42424242424242424242424242424242))

Output: Optional("42 seconds").

Expected: Because this collapses the "largest unit" - seconds in this case -, it's expected to be something like (Optional("42.42424242424242424242424242424242 * 1e^9")).

2nd Scenario

let fooFormatter = DateComponentsFormatter()

fooFormatter.allowedUnits = [.second, .nanosecond]
fooFormatter.unitsStyle = .full
fooFormatter.allowsFractionalUnits = true

print(fooFormatter.string(from: 42.42))

Output: Optional("42 seconds").

Expected: Even without opting to not collapse the .second, I expected anything close to (Optional("42 seconds 0.42 * 1e^9 nanoseconds")).

3rd Scenario

let fooFormatter = DateComponentsFormatter()
fooFormatter.allowedUnits = [.nanosecond]
fooFormatter.unitsStyle = .full
fooFormatter.allowsFractionalUnits = true

print(fooFormatter.string(from: 42.424242))

Output: nil.

Expected: Now it won't even recognize the TimeInterval as valid - when it's defined as the smallest fraction possible - and obviously expected everything in nanoseconds.

It's important to notice that I've used allowsFractionalUnits = true, which is even more alarming, because this behavior is also not working in the outputs given above (see the intended behavior here).

Thanks in advance.


Solution

  • DateComponentsFormatter does not support nanoseconds.

    See the documentation for allowedUnits, which does not include nanoseconds. It says:

    The allowed calendar units are:

    • year
    • month
    • weekOfMonth
    • day
    • hour
    • minute
    • second

    Assigning any other calendar units to this property results in an exception.