Swift: Get 30 days before 'Specific Date' [duplicate]

六月ゝ 毕业季﹏ 提交于 2019-12-19 19:45:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!