Skip to content

Instantly share code, notes, and snippets.

@Harinder
Created September 28, 2014 07:09
Show Gist options
  • Save Harinder/6d69c9db96b025884cc9 to your computer and use it in GitHub Desktop.
Save Harinder/6d69c9db96b025884cc9 to your computer and use it in GitHub Desktop.
Calculate dates one year in the past or one year in the future
import Foundation
/// Return date that is exactly one year earlier than specified date
///
/// :param: date NSDate
/// :returns: NSDate that is one year before date
func oneYearBeforeDate(date: NSDate) -> NSDate {
let offsetComponents = NSDateComponents()
offsetComponents.year = -1
let calendar = NSCalendar.currentCalendar()
if let result = calendar.dateByAddingComponents(offsetComponents, toDate: date, options: NSCalendarOptions(0)) {
return result
}
else {
// This should never happen, but we'll try to handle it gracefully
let secondsPerYear: NSTimeInterval = 60 * 60 * 24 * 365
return date.dateByAddingTimeInterval(-secondsPerYear)
}
}
/// Return date that is exactly one year later than specified date
///
/// :param: date NSDate
/// :returns: NSDate that is one year beyond date
func oneYearAfterDate(date: NSDate) -> NSDate {
let offsetComponents = NSDateComponents()
offsetComponents.year = 1
let calendar = NSCalendar.currentCalendar()
if let result = calendar.dateByAddingComponents(offsetComponents, toDate: date, options: NSCalendarOptions(0)) {
return result
}
else {
// This should never happen, but we'll try to handle it gracefully
let secondsPerYear: NSTimeInterval = 60 * 60 * 24 * 365
return date.dateByAddingTimeInterval(secondsPerYear)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment