如何在 Swift 3 中检查给定日期在 x 天以内 [英] How to check a given date was within a x number of days in Swift 3

查看:28
本文介绍了如何在 Swift 3 中检查给定日期在 x 天以内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定天数和特定日期的变量,我们如何检查给定的日期是否在过去的天数内.

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.

换句话说,我如何检查 dateVar 是否在过去 7 天内或数字的任何值.

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"

推荐答案

首先你需要将你的日期字符串转换为 Date 对象,然后你可以使用 DateComponent 来查找该日期与当前日期之间的天数差异,并将这些天数与您的数字进行比较,类似这样的事情.

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

这篇关于如何在 Swift 3 中检查给定日期在 x 天以内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆