Comparing NSDate

牧云@^-^@ 提交于 2019-12-21 19:49:04

问题


I would like to compare two NSDates however every date shows as being "Earlier" than todaysDate. Any ideas?

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

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

To get "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)

This print is:

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

and the print for "date" is:

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

This is on a Parse.com server.

Thanks


回答1:


I think perhaps you're interpreting the results of compare backwards. Check this out. Each of the asserts passes:

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



回答2:


If you want to support ==, <, >, <=, or >= for NSDates, you just have to declare this somewhere:

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

Implementing == and < lets Comparable infer the other comparison operators.

Usage:

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

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



回答3:


try this! you can check for different date by assigning it to 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")
    }


来源:https://stackoverflow.com/questions/26889382/comparing-nsdate

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