Question
Why is string
nil?
let formatter = NSDateComponentsFormatter()
let referenceDate = NSDate(timeIntervalSinceReferenceDate: 0)
let intervalDate = NSDate(timeInterval: 3628810, sinceDate: referenceDate)
let string = formatter.stringFromDate(referenceDate, toDate: intervalDate)
I'm expecting a string like "6w 10s" to be returned.
(6 weeks is 3,628,800 seconds.)
Attempted Troubleshooting
To troubleshoot, I tried setting allowedUnits
:
formatter.allowedUnits = .YearCalendarUnit | .MonthCalendarUnit | .WeekCalendarUnit | .DayCalendarUnit | .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit
Which results in this error:
"NSInvalidArgumentException", "Specifying positional units with gaps is ambiguous, and therefore unsupported"
I don't know what a "positional unit" is (outside of football), and I don't think I'm specifying any gaps.
Notes
I'm not using stringFromTimeInterval()
because that will return different results depending on the system's current date. (i.e., February only has 28/29 days in a month.) I want to calculate the time interval from the NSDate
reference date.
I'm using Xcode 6.1.1 (6A2008a). Here's a Playground screenshot if that helps:
From the headerdoc:
So:
When we omit one of them in the middle:
'Specifying positional units with gaps is ambiguous, and therefore unsupported'
error :) That is the "gap" means, I think.Not specifying a unit style will cause this in Swift 4 and 5.
Other unit styles:
.spellOut
,.short
,.brief
,.abbreviated
,.positional
Swift 3.0 version for Solving this.
Now here the difference is giving all the value of allowUnits from ascending or descending order.
This works for me to get rid of the "gaps":