Last active
May 22, 2017 13:24
-
-
Save bennokress/7c4ab11f7442bee82d3b103603e6b620 to your computer and use it in GitHub Desktop.
Extensions for Swift's Date Type
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
extension Date { | |
var isToday: Bool { return Calendar.current.isDateInToday(self) } | |
/// Returns a Date with the specified days added to the one it is called with | |
func adding(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date { | |
var targetDay: Date | |
targetDay = Calendar.current.date(byAdding: .year, value: years, to: self)! | |
targetDay = Calendar.current.date(byAdding: .month, value: months, to: targetDay)! | |
targetDay = Calendar.current.date(byAdding: .day, value: days, to: targetDay)! | |
targetDay = Calendar.current.date(byAdding: .hour, value: hours, to: targetDay)! | |
targetDay = Calendar.current.date(byAdding: .minute, value: minutes, to: targetDay)! | |
targetDay = Calendar.current.date(byAdding: .second, value: seconds, to: targetDay)! | |
return targetDay | |
} | |
/// Returns a Date with the specified days subtracted from the one it is called with | |
func subtracting(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date { | |
let inverseYears = -1 * years | |
let inverseMonths = -1 * months | |
let inverseDays = -1 * days | |
let inverseHours = -1 * hours | |
let inverseMinutes = -1 * minutes | |
let inverseSeconds = -1 * seconds | |
return add(years: inverseYears, months: inverseMonths, days: inverseDays, hours: inverseHours, minutes: inverseMinutes, seconds: inverseSeconds) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment