Last active
March 23, 2016 14:25
-
-
Save ryantxr/8a0db817f44da977018d to your computer and use it in GitHub Desktop.
Date ranges with NSCalendar in Swift
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
print("Day test = \(rangeOfPeriod(.Day, date: NSDate()))") | |
print("Week test = \(rangeOfPeriod(.WeekOfYear, date: NSDate()))") | |
print("month test = \(rangeOfPeriod(.Month, date: NSDate()))") | |
print("Year test = \(rangeOfPeriod(.Year, date: NSDate()))") |
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
func rangeOfPeriod(period: NSCalendarUnit, date: NSDate) -> (NSDate, NSDate) { | |
let calendar = NSCalendar.currentCalendar() | |
var startDate: NSDate? = nil | |
var duration: NSTimeInterval = 0 | |
calendar.rangeOfUnit(period, startDate: &startDate, interval: &duration, forDate: date) | |
let endDate = startDate!.dateByAddingTimeInterval(duration - 1) | |
return (startDate!, endDate) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment