问题
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 its still not working. Thanks in Advance.
*Note : I dont have any DatePicker in this controller
回答1:
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)
回答2:
You can use the following code:
let today = Date() //Jun 21, 2017, 7:18 PM
let thirtyDaysBeforeToday = Calendar.current.date(byAdding: .day, value: -30, to: today)! //May 22, 2017, 7:18 PM
I hope this helps.
来源:https://stackoverflow.com/questions/44688978/swift-get-30-days-before-specific-date