swiftnsdatecomponentsformatter

Swift 2.0: NSDateComponentsFormatterUnitsStyle alternative?


I am using a datePicker to choose a date, and a label to show the amount of days until the chosen date.

I am Using the ¨_formatter.unitsStyle = .Positional¨ to show the user the number of days that has been chosen, but i dont want the label to say: ¨30 days¨ or ¨30d¨ I only want it to say ¨30¨ Anyone know how i can do it?

None of the UnitStyles previewed on site seems to do that: http://nshipster.com/nsformatter/


Solution

  • If you just want the numeric value, use NSDateComponents:

    let components = NSCalendar.currentCalendar().components(.Day, fromDate: NSDate(), toDate: datePicker.date, options: [])
    label.text = String(components.day)
    

    or, if that number is going to be very large and would benefit from localized formatting, format that number with NSNumberFormatter:

    let formatter = NSNumberFormatter()
    formatter.numberStyle = .DecimalStyle
    label.text = formatter.stringFromNumber(components.day)