如何知道两个NSDate是否在同一天

khe*_*aud 7 iphone cocoa nsdate

你知道怎么知道两个NSDate是否是同一天.我想考虑一下本地化......

这可能很容易使用,timeIntervalSinceDate:但周一23H58和周二00H01不在同一天...

处理NSDate和区域设置计算并不容易.

Ter*_*cox 18

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *componentsForFirstDate = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:firstDate];

NSDateComponents *componentsForSecondDate = [calendar components:NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit fromDate:secondDate];

if ([componentsForFirstDate year] == [componentsForSecondDate year])
Run Code Online (Sandbox Code Playgroud)

等等

我不知道是否isEquals能做你想做的事NSDateComponents.

  • 从iOS 7开始,`[NSCalendar currentCalendar]`由操作系统缓存,因此不再需要在本地缓存. (4认同)

ren*_*ene 10

从iOS 8开始,这很简单:

let isSameDay = NSCalendar.currentCalendar().isDate(date1, inSameDayAsDate: date2)
Run Code Online (Sandbox Code Playgroud)

使用Swift 3它变得有点简单:

let isSameDay = Calendar.current.isDate(date1, inSameDayAs: date2)
Run Code Online (Sandbox Code Playgroud)


Vla*_*mir 7

使用NSCalendar和NSDateComponents:

NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comps1 = [cal components:(NSMonthCalendarUnit| NSYearCalendarUnit | NSDayCalendarUnit) 
                                      fromDate:date1];
NSDateComponents *comps2 = [cal components:(NSMonthCalendarUnit| NSYearCalendarUnit | NSDayCalendarUnit) 
                                      fromDate:date2];


BOOL sameDay = ([comps1 day] == [comps2 day] 
                  && [comps1 month] == [comps2 month] 
                  && [comps1 year] == [comps2 year]);
Run Code Online (Sandbox Code Playgroud)


Ale*_*kov 6

迅速:

func isSameDays(date1:NSDate, _ date2:NSDate) -> Bool {
    let calendar = NSCalendar.currentCalendar()
    var comps1 = calendar.components([NSCalendarUnit.Month , NSCalendarUnit.Year , NSCalendarUnit.Day], fromDate:date1)
    var comps2 = calendar.components([NSCalendarUnit.Month , NSCalendarUnit.Year , NSCalendarUnit.Day], fromDate:date2)

    return (comps1.day == comps2.day) && (comps1.month == comps2.month) && (comps1.year == comps2.year)
}
Run Code Online (Sandbox Code Playgroud)


oqu*_*oqu 5

使用NSDateFormatter执行此操作:

NSDateFormatter *_df = [[NSDateFormatter alloc] init];
_df.dateFormat = @"yyyy.MM.dd";
NSString *_d1 = [_df stringFromDate:_date1];
NSString *_d2 = [_df stringFromDate:_date2];
if ([_d1 isEqualToString:_d2] == YES)
{
    // d1 and d2 is on same day/month/year
}
[_df release];
Run Code Online (Sandbox Code Playgroud)