Dates & Components in Swift 2.0

Another topic that has been changed in Swift 2.0 is how to work with dates.

I’m digging into this topic for my upcoming app and I’ve found that most documentation on the web refers to Swift 1.2. So here are some snippets to create dates using components:

//CreateDateFromComponents (1st January 2016)

       var newDate = NSDate()

       let newDateComponents: NSDateComponents = NSDateComponents()

       newDateComponents.setValue(1, forComponent: NSCalendarUnit.Day)

       newDateComponents.setValue(1, forComponent: NSCalendarUnit.Month)

       newDateComponents.setValue(2016, forComponent: NSCalendarUnit.Year)

       newDate = NSCalendar.currentCalendar().dateFromComponents(newDateComponents)!

 

//AddToDateFromComponents (1 day, 1 month and 1 year to today)

 

        var newDate = NSDate()

        let newDateComponentsWhereQueryShouldBegin: NSDateComponents = NSDateComponents()

        newDateComponents.setValue(1, forComponent: NSCalendarUnit.Day)

        newDateComponents.setValue(1, forComponent: NSCalendarUnit.Month)

        newDateComponents.setValue(1, forComponent: NSCalendarUnit.Year)

        newDate = NSCalendar.currentCalendar().dateByAddingComponents(newDateComponents, toDate: newDate, options: NSCalendarOptions(rawValue: 0))! 

 

Hope this proves useful. If you would have any suggestions on how to improve you know where to reach me, @MarcMasVi in Twitter.

 

Marc