比较NSDate

时间:2014-11-12 14:29:44

标签: swift compare nsdate

我想比较两个NSDates但是每个日期显示为“早于” todaysDate 。有什么想法吗?

let compareResult = self.todaysDate.compare(self.date)

if compareResult == NSComparisonResult.OrderedDescending {
println("Today is later than date2")
} else {
println("Future")
}

获取“todaysDate”

let todaysDate = NSDate()
let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: todaysDate)
let hour = components.hour
let minutes = components.minute
let month = components.month
let year = components.year
let day = components.day
println(todaysDate)

此印刷品是:

2014-11-12 14:48:48 +0000

“date”的打印是:

2014-10-24 07:24:41 +0000

这是在Parse.com服务器上。

由于

3 个答案:

答案 0 :(得分:10)

我想也许你正在向后解释compare的结果。看一下这个。每个asserts次传递:

let today = NSDate()
let tomorrow = today.dateByAddingTimeInterval(24 * 60 * 60)
let yesterday = today.dateByAddingTimeInterval(-24 * 60 * 60)

assert(today.compare(tomorrow)  == .OrderedAscending)     // today < tomorrow
assert(today.compare(yesterday) == .OrderedDescending)    // today > yesterday
assert(today.compare(today)     == .OrderedSame)          // today == today

答案 1 :(得分:10)

如果您想为==支持<><=>=NSDate,则必须在某处声明:

public func ==(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs === rhs || lhs.compare(rhs) == .OrderedSame
}

public func <(lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.compare(rhs) == .OrderedAscending
}

extension NSDate: Comparable { }

实施==<Comparable推断其他比较运算符。

用法:

let date1 = NSDate()
let date2 = NSDate()

println(date2 > date1) // true
println(date2 < date1) // false
println(date2 == date2) // true

答案 2 :(得分:1)

试试这个!您可以通过将其分配给strdate来检查不同的日期

    todaysDate = NSDate()
    println(todaysDate)

    var dateformmatter:NSDateFormatter = NSDateFormatter()
    dateformmatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
    let strdate:NSString = "2014-12-12 07:24:41";
    date = dateformmatter.dateFromString(strdate)!;
    println(date)

    let compareResult = todaysDate.compare(date)

    if compareResult == NSComparisonResult.OrderedDescending {
        println("Today is later than date2")
    } else {
        println("Future")
    }