Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

64
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!