检查日期是否介于 2 个日期之间 [英] Check if date falls between 2 dates
本文介绍了检查日期是否介于 2 个日期之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有将字符串转换为日期对象的代码
I have this code where convert a String into a date object
let date2 = KeysData[indexPath.row]["starttime"] as? String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
if let date = dateFormatter.dateFromString(date2!) {
println(date)
}
我想知道当前日期是否介于我在数组 startdate
和 endate
I would like to know if the current date falls between the 2 days i got in the array startdate
and endate
推荐答案
Swift 2
有关更好的答案,请参阅 Swift ≧ 3.
您已经拥有将 KeysData
中的日期字符串转换为 NSDate
的代码.假设您在 startdate
和 enddate
中有两个日期,您所要做的就是检查当前日期是否介于两者之间:
You already have the code for conversion of your date string in KeysData
to NSDate
. Assuming you have the two dates in startdate
and enddate
, all you have to do is check if the current date is in between:
let startDate = ...
let endDate = ...
NSDate().isBetween(date: startDate, andDate: endDate)
extension NSDate {
func isBetweeen(date date1: NSDate, andDate date2: NSDate) -> Bool {
return date1.compare(self) == self.compare(date2)
}
}
如果要执行包含范围检查,请使用以下条件:
If you want to perform an inclusive range check, use this condition:
extension NSDate {
func isBetween(date date1: NSDate, andDate date2: NSDate) -> Bool {
return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
}
}
这篇关于检查日期是否介于 2 个日期之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文