Search code examples
swiftnsdatenscalendar

Number to Date - Swift


Getting the day of year is straightforward, e.g.

func dayOfYear(inputDate:NSDate) -> (Int) {
    let cal         = NSCalendar.currentCalendar()
    let returnDay   = cal.ordinalityOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitYear, forDate: inputDate)
    return returnDay
}

But how do you do the reverse? It would obviously return just the day/month. I can easily write a tedious routine back-calculating but is there a smart way?


Solution

  • Yes, NSCalendar provides a way to coalesce calendar components into a single date object. Take a look at this example I wrote in a Playground:

    import UIKit
    import Foundation
    
    let inputDate: NSDate = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let day = calendar.ordinalityOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitYear, forDate: inputDate)
    
    let components = NSDateComponents()
    components.day = day
    
    let date = calendar.dateFromComponents(components)
    

    According to the documentation,

    When there are insufficient components provided to completely specify an absolute time, a calendar uses default values of its choice. When there is inconsistent information, a calendar may ignore some of the components parameters or the method may return nil. Unnecessary components are ignored (for example, Day takes precedence over Weekday and Weekday ordinals).

    Furthermore,

    Note that some computations can take a relatively long time to perform.

    See the NSCalendar Class Reference for more information.