简体   繁体   中英

Swift get date five years prior to today

I have this validation code, I want to add another part to it where it checks to make sure that the date selected in not more than fives years in the past from today. Thoughts!

let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .medium
    let date1 = dateFormatter.date (from: termStartDate.text!)

    guard let startDate = date1 , startDate < Date() else {
        let alert = UIAlertController(title: "Input Error", message: "Select Date less than today", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
        return
    }

You can grab the date five years back from now with this one-liner:

let fiveYearsAgoDate = Calendar.current.date(byAdding: .year, value: -5, to: Date())

Since you may not be using a UIDatePicker (many apps use a numeric key pad that inserts separators, such as / , between days, months, and years), this is a viable option to validate user input. Otherwise, if using a UIDatePicker , setting the maximum and minimum dates is the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM