Last active
August 29, 2015 14:27
-
-
Save nRewik/55296ffbcb60e3b26541 to your computer and use it in GitHub Desktop.
Create all dates in specific month and year as in `gregorian` calendar
This file contains 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
import UIKit | |
extension NSDate{ | |
/** | |
Create all dates in specific month and year as in `gregorian` calendar | |
**Usage Example** | |
`NSDate.datesInMonthCalendar(month: 8, year: 2015)` | |
`26 27 28 29 30 31 1` | |
`2 3 4 5 6 7 8` | |
`9 10 11 12 13 14 15` | |
`16 17 18 19 20 21 22` | |
`23 24 25 26 27 28 29` | |
`30 31 1 2 3 4 5` | |
:param: Month,Year | |
:returns: [NSDate], contains 6 weeks, the size equals 6 * 7 = 42 | |
*/ | |
class func datesInCalendar( #month: Int, year: Int ) -> [NSDate]{ | |
var datesInMonthCalendar = [NSDate]() | |
let cal = NSCalendar(identifier: "gregorian")! | |
let components = NSDateComponents() | |
components.year = year | |
components.month = month | |
components.day = 1 | |
for i in 0..<6{ | |
var aDateInThatWeek = cal.dateFromComponents(components)! | |
var startOfTheWeek: NSDate? | |
var interval: NSTimeInterval = 0.0 | |
cal.rangeOfUnit( .CalendarUnitWeekOfMonth, startDate: &startOfTheWeek, interval: &interval, forDate: aDateInThatWeek) | |
var endOfWeek = startOfTheWeek!.dateByAddingTimeInterval(interval-1) | |
let dmyOptions = NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | |
let startDayComponents = cal.components( dmyOptions, fromDate: startOfTheWeek!) | |
let endDayComponents = cal.components( dmyOptions, fromDate: endOfWeek) | |
var currentComponent = startDayComponents | |
var xDate = cal.dateFromComponents(startDayComponents)! | |
var endDate = cal.dateFromComponents(endDayComponents)! | |
// iterate from start day of a week til the end of week. | |
while(xDate.compare(endDate) == .OrderedAscending || xDate.compare(endDate) == .OrderedSame){ | |
let resultDay = cal.component( .CalendarUnitDay, fromDate: xDate) | |
let resultMonth = cal.component(.CalendarUnitMonth, fromDate: xDate) | |
datesInMonthCalendar += [xDate] | |
currentComponent.day += 1 | |
xDate = cal.dateFromComponents(currentComponent)! | |
} | |
components.day = currentComponent.day | |
components.month = currentComponent.month | |
components.year = currentComponent.year | |
} | |
return datesInMonthCalendar | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment