比较 NSDate

Comparing NSDate(比较 NSDate)
本文介绍了比较 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 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 { }

实现 ==<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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Why local notification is not firing for UNCalendarNotificationTrigger(为什么没有为UNCalendarNotificationTrigger触发本地通知)
Pushing UIViewController above UITabBar(将UIView控制器推送到UITabBar上方)
Dropbox Files.download does not start when number of files in folder is gt; 1000(当文件夹中的文件数为1000时,Dropbox Files.Download不会启动)
appearance().setBackgroundImage Not Working On Custom Class(外观().setBackoundImage在自定义类上不起作用)
Show/Hide barButtonItem(显示/隐藏barButtonItem)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)