检查日期是否介于两个日期之间

时间:2015-09-30 06:48:37

标签: swift

我有这个代码将String转换为日期对象

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

我想知道当前日期是否属于我在数组startdateendate

中的2天之间

7 个答案:

答案 0 :(得分:97)

Swift≧3

Swift 3让这更容易。

let fallsBetween = (startDate ... endDate).contains(Date())

既然NSDate已桥接到值类型DateDate符合Comparable,我们就可以形成ClosedRange<Date>并使用{{1}查看当前日期是否包含的方法。

警告:contains必须大于或等于endDate。否则无法形成范围,代码会因startDate而崩溃。

这是安全的:

fatalError

答案 1 :(得分:51)

Swift 2

要获得更好的答案,请参阅Swift ≧ 3

您已拥有将日期字符串转换为KeysDataNSDate的代码。假设您在startdateenddate中有两个日期,您所要做的就是检查当前日期是否介于两者之间:

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

修改:如果您要执行包含范围检查,请使用以下条件:

 extension NSDate {
    func isBetween(date date1: NSDate, andDate date2: NSDate) -> Bool {
        return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
    }
}

答案 2 :(得分:3)

对于Swift 4.2,我根据上述答案使用了此扩展名:

extension Date {
    func isBetween(_ date1: Date, and date2: Date) -> Bool {
        return (min(date1, date2) ... max(date1, date2)) ~= self
    }

但是要小心。如果此扩展名不包含您的开始日期(date1),请检查日期。可能是您需要缩短日期才能解决问题。例如,像这样:

let myDateWithoutTime = Calendar.current.startOfDay(for: myDate)

答案 3 :(得分:2)

extension Date
{
    func isBetween(startDate:Date, endDate:Date)->Bool
    {
         return (startDate.compare(self) == .orderedAscending) && (endDate.compare(self) == .orderedDescending)
    }
}

答案 4 :(得分:1)

这里没有一个答案明确地涵盖了可能更精确的边界测试,这些边界测试在开始和结束之间有所不同。

例如从0900开始到1000结束的事件应具有返回以下结果的情况:

 <xsl:when test="hl7v3:title='event.description'">
     <div>
        <p style="white-space: pre-wrap; text-align:left;"><xsl:copy-of select="./hl7v3:text/hl7v3:paragraph/text()" /></p>
     </div>
 </xsl:when>

如果这是您想要的结果,那么以下扩展名将为您工作:

08:59:59    false
09:00:00    true
09:59:59    true
10:00:00    false

答案 5 :(得分:1)

DateInterval 有一个 .contains 函数用于此 (see docs):

extension Date {
    func isBetween(_ date1: Date, _ date2: Date) -> Bool {
        date1 < date2
            ? DateInterval(start: date1, end: date2).contains(self)
            : DateInterval(start: date2, end: date1).contains(self)
    }
}

然后你像这样使用它:

let date = Date()
let date1 = Date(timeIntervalSinceNow: 1000)
let date2 = Date(timeIntervalSinceNow: -1000)
date.isBetween(date1, date2) // true

请注意,如果您需要,它包括结束日期,或者添加一个 guard 来捕获它:

guard self != max(date1, date2) || self == min(date1, date2) else { return false }

经过一些重构后,您最终会得到这样的结果:

extension Date {
    func isBetween(_ date1: Date, _ date2: Date) -> Bool {
        let minDate = min(date1, date2)
        let maxDate = max(date1, date2)

        guard self != minDate else { return true }
        guard self != maxDate else { return false }

        return DateInterval(start: minDate, end: maxDate).contains(self)
    }
}

然后这将通过以下测试用例:

XCTAssert(
    try XCTUnwrap(Date(fromString: "2020/01/15 09:30")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 09:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00"))
    )
)

XCTAssert(
    try XCTUnwrap(Date(fromString: "2020/01/16 01:00")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 23:00")),
        try XCTUnwrap(Date(fromString: "2020/01/16 04:00"))
    )
)

XCTAssert(
    try XCTUnwrap(Date(fromString: "2020/01/15 10:00")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 10:30"))
    )
)

XCTAssert(
    try XCTUnwrap(Date(fromString: "2020/01/15 10:00")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00"))
    )
)

XCTAssert(
    try XCTUnwrap(Date(fromString: "2020/01/15 09:00")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 08:00"))
    )
)

XCTAssert(
    try XCTUnwrap(Date(fromString: "2020/01/15 08:00")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 08:00"))
    )
)

XCTAssertFalse(
    try XCTUnwrap(Date(fromString: "2020/01/15 09:00")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 13:00"))
    )
)

XCTAssertFalse(
    try XCTUnwrap(Date(fromString: "2020/01/15 10:30")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 10:30"))
    )
)

XCTAssertFalse(
    try XCTUnwrap(Date(fromString: "2020/01/15 10:00")).isBetween(
        try XCTUnwrap(Date(fromString: "2020/01/15 10:00")),
        try XCTUnwrap(Date(fromString: "2020/01/15 08:00"))
    )
)

let date = Date()
let date1 = Date(timeIntervalSinceNow: 1000)
let date2 = Date(timeIntervalSinceNow: -1000)
XCTAssert(date.isBetween(date1, date2))

答案 6 :(得分:-1)

extension Date {

    func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
        return date1.timeIntervalSince1970 < self.timeIntervalSince1970 && date2.timeIntervalSince1970 > self.timeIntervalSince1970
    }

}