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

点点圈 提交于 2019-12-11 04:49:45

问题


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"

回答1:


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")
    }
}


来源:https://stackoverflow.com/questions/40863559/how-to-check-a-given-date-was-within-a-x-number-of-days-in-swift-3

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