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

Viewed 1995

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?

3 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
}

Add below extension:

extension Date {
    func get(_ components: Calendar.Component..., calendar: Calendar = Calendar.current) -> DateComponents {
        return calendar.dateComponents(Set(components), from: self)
    }

    func get(_ component: Calendar.Component, calendar: Calendar = Calendar.current) -> Int {
        return calendar.component(component, from: self)
    }
}

Use extension as below:

let date = Date()

let components = date.get(.day, .month, .year)
if let day = components.day, let month = components.month, let year = components.year {
    print("day: \(day), month: \(month), year: \(year)")
}

For getting last week date exact from today

let lastWeekDate = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: 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)
  • To Add date pass prospective value
  • To Subtract pass negative value
Related