SwiftStarter SwiftStarter - 6 months ago 42
Swift Question

How to check a given date was within a x number of days in Swift 3

Given a variable for number of days and a specific date,
how can we check if the date given is within the past number of days.

In other words how can I check if dateVar was within the last 7 days or whatever the value of number is.

var number = 7

var dateVar = "29-11-2016 13:21:33"


First you need to convert you date string to Date object and then you can use DateComponent to find the difference between that date and current date in days and compare that days with you number, something like this.

let dateVar = "29-11-2016 13:21:33"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
if let date = dateFormatter.date(from: dateVar) {
    let numberOfDays = Calendar.current.dateComponents([.day], from: date, to: Date()).day ?? 0
    if numberOfDays <= number {
         print("DateVar with in number of days")