Search code examples
swiftdatedatepicker

Swift: Get 30 days before 'Specific Date'


I have a problem about showing specific date. Here the case, I have a random date from my API (06/16/2015) that always change. I put it into variable name toDate with Date type. I need to get 30 days before the toDate for my fromDate variable.

I read this but it's still not working. Note: I don't have any DatePicker in this controller.


Solution

  • Here you go:

    let toDate = `your date object`
    let fromDate = Calendar.current.date(byAdding: .month, value: -1, to: toDate)
    
    or, 
    // If you want to have exactly 30 days before
    let fromDate = Calendar.current.date(byAdding: .day, value: -30, to: toDate)