Contact Us

Use the form on the right to contact us.

You can edit the text in this area, and change where the contact form on the right submits to, by entering edit mode using the modes on the bottom right. 


Oak Ridge, TN, 37830
United States

Swift-Snips

Dates in Swift

Wade Cantley

The challenge I had was trying to break down date info for an app that was going to keep track of the current week as well as the current day.  For that, I really needed to figure out how to break out these parts into something I could use.

After a little looking online, I found some hints and I put together the below in a swift playground.  It is not comprehensive but should get you started.


import Cocoa
import Foundation

//Get the date
let date = NSDate()

// Define the parts you want
let flags: NSCalendarUnit = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitWeekdayOrdinal | NSCalendarUnit.CalendarUnitWeekday

// Setup the calculator class
let cal = NSCalendar.currentCalendar()

// combine the parts desired with the current date into the components variable.
let components = cal.components(flags, fromDate: date)

//The Parts
println(components.year)
println(components.month)
println(components.day)
println(components.weekOfYear)
println(components.weekdayOrdinal)
println(components.weekday)


//Gets day of the year
let day = cal.ordinalityOfUnit(.CalendarUnitDay, 
   inUnit: .CalendarUnitYear, forDate: date)