Hello I want to subtract days, months or a year from my current date. I can use this code to create a date which is one week away from the current date.
let date = Date().addingTimeInterval(TimeInterval(86400*7))
Is it possible to create a date which is one week in the past from the current date?
You should use Calendar to do these calculations instead of hard coding 86400 for a day.
if let date = Calendar.current.date(byAdding: .day, value: -7, to: Date()) {
// Use this date
}
Swift 5
Function to add or subtract day, month, year from current date.
func addOrSubtractDay(day:Int)->Date{
return Calendar.current.date(byAdding: .day, value: day, to: Date())!
}
func addOrSubtractMonth(month:Int)->Date{
return Calendar.current.date(byAdding: .month, value: month, to: Date())!
}
func addOrSubtractYear(year:Int)->Date{
return Calendar.current.date(byAdding: .year, value: year, to: Date())!
}
Now calling the function
//Subtracting
var daySubtractedDate = addOrSubtractDay(-7)
var monthSubtractedDate = addOrSubtractMonth(-7)
var yearSubtractedDate = addOrSubtractYear(-7)
//Adding
var dayAddedDate = addOrSubtractDay(7)
var monthAddedDate = addOrSubtractMonth(7)
var yearAddedDate = addOrSubtractYear(7)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With