Skip to content

Instantly share code, notes, and snippets.

@dgyesbreghs
Created June 30, 2015 12:29
Show Gist options
  • Save dgyesbreghs/5e1ddbfb3e85643ba706 to your computer and use it in GitHub Desktop.
Save dgyesbreghs/5e1ddbfb3e85643ba706 to your computer and use it in GitHub Desktop.
Get first day of a week with Swift
//: Playground - noun: a place where people can play
import UIKit
let today = NSDate.new()
let gregorian = NSCalendar.currentCalendar()
let weekdayComponetns = gregorian.components(NSCalendarUnit.Weekday, fromDate: today)
let compontentsToSubstract = NSDateComponents.new()
// Sunday -> -(weekdayComponetns.weekday - gregorian.firstWeekday)
// Monday -> -(weekdayComponetns.weekday - gregorian.firstWeekday - 1)
compontentsToSubstract.day = -(weekdayComponetns.weekday - gregorian.firstWeekday - 1)
var beginningOfWeek = gregorian.dateByAddingComponents(compontentsToSubstract, toDate: today, options: NSCalendarOptions(rawValue: 0))
let components = gregorian.components(([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day]), fromDate: beginningOfWeek!)
beginningOfWeek = gregorian.dateFromComponents(components)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment