为了账号安全,请及时绑定邮箱和手机立即绑定

iOS:比较两个日期

iOS:比较两个日期

iOS
缥缈止盈 2019-10-28 10:36:14
我有一个NSDate,我必须和另外两个比较NSDate,我试着用NSOrderAscending和NSOrderDescending,但如果我的日期是在其他两个日期平等吗?示例:如果我有一个a myDate = 24/05/2011 和另外两个分别为one = 24/05/2011和2,24/05/2011该怎么用?
查看完整描述

3 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

根据苹果的文件NSDate compare:


返回一个NSComparisonResult值,该值指示接收者的时间顺序和另一个给定的日期。


- (NSComparisonResult)compare:(NSDate *)anotherDate


参量 anotherDate


比较接收者的日期。此值不能为nil。如果值为nil,则行为是未定义的,并且在Mac OS X的将来版本中可能会更改。


返回值


如果:


接收者和anotherDate彼此完全相同, NSOrderedSame


接收器的时间晚于另一个日期, NSOrderedDescending


接收者的时间早于另一个日期, NSOrderedAscending


换一种说法:


if ([date1 compare:date2] == NSOrderedSame) ...

请注意,在您的特定情况下,阅读和编写以下内容可能会更容易:


if ([date2 isEqualToDate:date2]) ...


查看完整回答
反对 回复 2019-10-28
?
千巷猫影

TA贡献1829条经验 获得超7个赞

我不知道您是否曾问过这个问题,但是如果您只想比较NSDate的日期部分,则必须使用NSCalendar和NSDateComponents删除时间部分。


这样的事情应该作为NSDate的类别:


- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {

    NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;

    NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];

    NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];

    NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];


    NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];

    NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];

    return [selfDateOnly compare:otherDateOnly];

}


查看完整回答
反对 回复 2019-10-28
  • 3 回答
  • 0 关注
  • 749 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信