我想比较两个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服务器上。
由于
答案 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)
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")
}