Created
June 30, 2015 12:29
-
-
Save dgyesbreghs/5e1ddbfb3e85643ba706 to your computer and use it in GitHub Desktop.
Get first day of a week with Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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