Reputation: 247
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"
Upvotes: 1
Views: 348
Reputation: 72410
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"
if let date = dateFormatter.date(from: dateVar) {
print(date)
let numberOfDays = Calendar.current.dateComponents([.day], from: date, to: Date()).day ?? 0
print(numberOfDays)
if numberOfDays <= number {
print("DateVar with in number of days")
}
}
Upvotes: 4