Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to subtract days, months or years from current date in swift

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?

like image 321
comhendrik Avatar asked Dec 10 '25 18:12

comhendrik


2 Answers

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
}
like image 52
Tarun Tyagi Avatar answered Dec 13 '25 15:12

Tarun Tyagi


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)
  • To Add date pass prospective value
  • To Subtract pass negative value
like image 23
Md. Enamul Haque Avatar answered Dec 13 '25 14:12

Md. Enamul Haque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!