What am I Doing Wrong with Allowsfractionalunits on Nsdatecomponentsformatter

NSDateComponentsFormatter adds additional hour

This is caused by Daylight saving time change which happens in Europe in a few days.
I am not sure whether this is the expected behavior of the interval formatter (it definitely seems a bit strange). However, as all time zone problems, you can fix it by setting the time zone to a specific GMT timezone. In this case GMT-00:00 is probably the expected time zone:

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Positional
formatter.allowedUnits = [.Year, .Month, .WeekOfMonth, .Day, .Hour, .Minute]

let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
calendar.locale = NSLocale.currentLocale()
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)

formatter.calendar = calendar

print(formatter.stringFromTimeInterval(3600)) // "1:00"
print(formatter.stringFromTimeInterval(3600*24)) // "1d 0:00"
print(formatter.stringFromTimeInterval(3600*24*5)) // "5d 0:00"
print(formatter.stringFromTimeInterval(3600*24*365)) // "1y 0m 0w 0d 0:00"

Getting screwy results from NSDateComponentsFormatter

It appears that the iOS 8.x and Mac OS 10.10 version of the NSDateComponentsFormatter is buggy. I get (intermittent!) different, wrong results for some dates in those OS versions, but correct results from the latest OS versions.

Sigh...

Format to MM:SS using NSDateComponentsFormatter

Sorry for wrong initial answer, there is no way to add leading zeros to hours:

When days, hours, minutes, and seconds are allowed, the value is displayed as “0d 1:00:00” using the positional style, and as “0d 1h 0m 0s” using the abbreviated style.

If you simply need to format NSTimeInterval into string like HH:MM:SS check this answer

NSDateComponentsFormatter Units Separator

If your application is targeting OS X 10.12 (or later, I presume) or iOS 10.10 (or later), then Apple added a new units style called "NSDateComponentsFormatterUnitsStyleBrief"

formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleBrief

and it will print out "1 hr 30 min"

https://developer.apple.com/reference/foundation/nsdatecomponentsformatterunitsstyle/nsdatecomponentsformatterunitsstylebrief?language=objc



Related Topics



Leave a reply



Submit