Created
September 28, 2014 07:09
-
-
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
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 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