本文介绍了比较 NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想比较两个 NSDate,但是每个日期都显示为早于"todaysDate.有什么想法吗?
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")
}
获取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 服务器上.
This is on a Parse.com server.
谢谢
推荐答案
如果要支持==
, <
, >
、<=
或 >=
用于 NSDate
,您只需在某处声明即可:
If you want to support ==
, <
, >
, <=
, or >=
for NSDate
s, 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 { }
实现 ==
和 <
让 Comparable
推断其他比较运算符.
Implementing ==
and <
lets Comparable
infer the other comparison operators.
用法:
let date1 = NSDate()
let date2 = NSDate()
println(date2 > date1) // true
println(date2 < date1) // false
println(date2 == date2) // true
这篇关于比较 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!