iOS:比较两个日期
我有一个 NSDate
,我必须将其与其他两个 NSDate
进行比较,并且我尝试使用 NSOrderAscending
和 NSOrderDescending
但如果我的其他两个日期的日期相等吗?
示例:如果我有一个 myDate = 24/05/2011
和另外两个,其中一个 = 24/05/2011
和两个 24/05/2011< /code> 我可以使用什么?
I have a NSDate
that I must compare with other two NSDate
and I try with NSOrderAscending
and NSOrderDescending
but if my date is equal at other two dates?
Example: if I have a myDate = 24/05/2011
and other two that are one = 24/05/2011
and two 24/05/2011
what can I use?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
根据
NSDate 比较的 Apple 文档:
换句话说:
请注意,在您的特定情况下,阅读和编写此内容可能会更容易:
请参阅有关此的 Apple 文档。
According to Apple documentation of
NSDate compare:
In other words:
Note that it might be easier in your particular case to read and write this :
See Apple Documentation about this one.
经过搜索,我得出的结论是,最好的方法是这样的:
您也可以将其更改为小时之间的差异。
如果您只想比较 dd/MM/yyyy 格式的日期,则需要在
NSDate* currentdate = [NSDate date];
&& 之间添加以下行NSTimeInterval距离
After searching, I've got to conclusion that the best way of doing it is like this:
You can change it to difference between hours also.
If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between
NSDate* currentdate = [NSDate date];
&&NSTimeInterval distance
我认为您是在问比较函数的返回值是什么。
如果日期相等,则返回 NSOrderedSame
如果升序(第 2 个参数 > 第 1 个参数),则返回 NSOrderedAscending
如果降序(第 2 个参数 < 第 1 个参数),则返回 NSOrderedDescending< /代码>
I take it you are asking what the return value is in the comparison function.
If the dates are equal then returning
NSOrderedSame
If ascending ( 2nd arg > 1st arg ) return
NSOrderedAscending
If descending ( 2nd arg < 1st arg ) return
NSOrderedDescending
我不确切知道您是否问过这个问题,但如果您只想比较 NSDate 的日期部分,则必须使用 NSCalendar 和 NSDateComponents 来删除时间部分。
像这样的东西应该作为 NSDate 的类别:
I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.
Something like this should work as a category for NSDate:
NSDate
实际上表示自参考日期(我认为 UTC 2000 年 1 月 1 日)以来的时间间隔(以秒为单位)。在内部,使用双精度浮点数,因此两个任意日期即使在同一天也不太可能比较相等。如果您想查看特定日期是否在特定日期,您可能需要使用NSDateComponents
。例如NSDate
actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to useNSDateComponents
. e.g.检查以下日期比较函数,首先创建两个 NSDate 对象并传递给该函数:
在 viewDidload 中或根据您的场景添加以下代码行。
这是函数
只需更改日期并测试上面的函数:)
Check the following Function for date comparison first of all create two NSDate objects and pass to the function:
Add the bellow lines of code in viewDidload or according to your scenario.
here is the function
Simply change the date and test above function :)