iOS:比较两个不带时间部分的 NSDate-s

发布于 2024-11-14 00:47:51 字数 1656 浏览 3 评论 0原文

我想比较两个日期:date1 和 date2,

2011-06-06 12:59:48.994 Project[419:707] firstDate:2011-06-06 10:59:21 +0000
2011-06-06 12:59:49.004 Project[419:707] selectedData:2011-06-06 10:59:17 +0000

但是这些日期有不同的时间,当我使用 NSOrderedSame 时它不能正常工作,我该如何解决?

我的代码:

NSDate *firstDate = [[appDelegate.project objectAtIndex:i]objectAtIndex:3];
NSDate *secondDate = [[appDelegate.project objectAtIndex:i]objectAtIndex:4];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDateComponents *date1Components = [calendar components:comps 
                                                            fromDate:firstDate];
NSDateComponents *date2Components = [calendar components:comps 
                                                            fromDate:secondDate];
NSDateComponents *date3Components = [calendar components:comps fromDate:appDelegate.selectedDate];

NSLog(@"firstDate:%@", [date1Components date]);
NSLog(@"secondDate:%@", [date2Components date]);
NSLog(@"selectedData:%@", [date3Components date]);

NSComparisonResult compareStart = [[date1Components date] compare: [date3Components date]]; 
NSComparisonResult compareEnd = [[date2Components date] compare: [date3Components date]]; 

if ((compareStart == NSOrderedAscending || compareStart == NSOrderedSame)
     && (compareEnd == NSOrderedDescending || compareEnd == NSOrderedSame))

{
    NSLog(@"inside");

然后,当 date1 <= selectedDate <= date2; 时,我想比较我的日期和“if”内的条目;现在我明白了,因为我有一个警告:我应该添加这个“[date1Components date]”并且它可以工作;问题是我的 NSLog 中有空值,为什么?

I want to compare two dates: date1 and date2

2011-06-06 12:59:48.994 Project[419:707] firstDate:2011-06-06 10:59:21 +0000
2011-06-06 12:59:49.004 Project[419:707] selectedData:2011-06-06 10:59:17 +0000

but these dates have different time and when I use NSOrderedSame it don't work fine, how can I solve?

my code:

NSDate *firstDate = [[appDelegate.project objectAtIndex:i]objectAtIndex:3];
NSDate *secondDate = [[appDelegate.project objectAtIndex:i]objectAtIndex:4];

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDateComponents *date1Components = [calendar components:comps 
                                                            fromDate:firstDate];
NSDateComponents *date2Components = [calendar components:comps 
                                                            fromDate:secondDate];
NSDateComponents *date3Components = [calendar components:comps fromDate:appDelegate.selectedDate];

NSLog(@"firstDate:%@", [date1Components date]);
NSLog(@"secondDate:%@", [date2Components date]);
NSLog(@"selectedData:%@", [date3Components date]);

NSComparisonResult compareStart = [[date1Components date] compare: [date3Components date]]; 
NSComparisonResult compareEnd = [[date2Components date] compare: [date3Components date]]; 

if ((compareStart == NSOrderedAscending || compareStart == NSOrderedSame)
     && (compareEnd == NSOrderedDescending || compareEnd == NSOrderedSame))

{
    NSLog(@"inside");

Then I want to compare my dates and entry inside the "if" when date1 <= selectedDate <= date2; now I understand because I have a warning: I should add this "[date1Components date]" and it work; the problem is that I have in the NSLog null values, why??

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

小巷里的女流氓 2024-11-21 00:47:51
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear);

NSDateComponents *date1Components = [calendar components:comps 
                                                fromDate: date1];
NSDateComponents *date2Components = [calendar components:comps 
                                                fromDate: date2];

date1 = [calendar dateFromComponents:date1Components];
date2 = [calendar dateFromComponents:date2Components];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
}  else {
    //the same
}

还有另一种方便的方法可以为给定日期创建代表给定单元开始的日期:[aCalendar rangeOfUnit:startDate:interval:forDate:]
要说明此方法的工作原理,请参阅此代码,它可以轻松创建给定日期的日、周、月和年的开始日期(此处:现在)。

NSDate *now = [NSDate date];
NSDate *startOfToday = nil;
NSDate *startOfThisWeek = nil;
NSDate *startOfThisMonth = nil;
NSDate *startOfThisYear = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startOfThisWeek interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSMonthCalendarUnit startDate:&startOfThisMonth interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSYearCalendarUnit startDate:&startOfThisYear interval:NULL forDate:now];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterFullStyle];

NSLog(@"%@", [formatter stringFromDate:now]);
NSLog(@"%@", [formatter stringFromDate:startOfToday]);
NSLog(@"%@", [formatter stringFromDate:startOfThisWeek]);
NSLog(@"%@", [formatter stringFromDate:startOfThisMonth]);
NSLog(@"%@", [formatter stringFromDate:startOfThisYear]);

结果:

Thursday, July 12, 2012, 4:36:07 PM Central European Summer Time 
Thursday, July 12, 2012, 12:00:00 AM Central European Summer Time 
Sunday, July 8, 2012, 12:00:00 AM Central European Summer Time 
Sunday, July 1, 2012, 12:00:00 AM Central European Summer Time 
Sunday, January 1, 2012, 12:00:00 AM Central European Standard Time

这允许我们将第一个代码缩短为:

[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date2 interval:NULL forDate:date2];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
}  else {
    //the same
}

注意,在此代码中,date1date2 将被覆盖。或者,您可以传递对 startDate 的另一个 NSDate 指针的引用,如上面的代码所示,其中 now 保持不变。

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger comps = (NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear);

NSDateComponents *date1Components = [calendar components:comps 
                                                fromDate: date1];
NSDateComponents *date2Components = [calendar components:comps 
                                                fromDate: date2];

date1 = [calendar dateFromComponents:date1Components];
date2 = [calendar dateFromComponents:date2Components];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
}  else {
    //the same
}

There is another handy method to create for a given date the date that represents the start of a given unit: [aCalendar rangeOfUnit:startDate:interval:forDate:]
To illustrate how this method works, see this code, that easily creates the date for the beginning of the day, week, month and year for a given date (here: now).

NSDate *now = [NSDate date];
NSDate *startOfToday = nil;
NSDate *startOfThisWeek = nil;
NSDate *startOfThisMonth = nil;
NSDate *startOfThisYear = nil;
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&startOfToday interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSWeekCalendarUnit startDate:&startOfThisWeek interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSMonthCalendarUnit startDate:&startOfThisMonth interval:NULL forDate:now];
[[NSCalendar currentCalendar] rangeOfUnit:NSYearCalendarUnit startDate:&startOfThisYear interval:NULL forDate:now];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterFullStyle];
[formatter setTimeStyle:NSDateFormatterFullStyle];

NSLog(@"%@", [formatter stringFromDate:now]);
NSLog(@"%@", [formatter stringFromDate:startOfToday]);
NSLog(@"%@", [formatter stringFromDate:startOfThisWeek]);
NSLog(@"%@", [formatter stringFromDate:startOfThisMonth]);
NSLog(@"%@", [formatter stringFromDate:startOfThisYear]);

result:

Thursday, July 12, 2012, 4:36:07 PM Central European Summer Time 
Thursday, July 12, 2012, 12:00:00 AM Central European Summer Time 
Sunday, July 8, 2012, 12:00:00 AM Central European Summer Time 
Sunday, July 1, 2012, 12:00:00 AM Central European Summer Time 
Sunday, January 1, 2012, 12:00:00 AM Central European Standard Time

this allows us to shorten the first code to:

[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date1 interval:NULL forDate:date1];
[[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit startDate:&date2 interval:NULL forDate:date2];

NSComparisonResult result = [date1 compare:date2];
if (result == NSOrderedAscending) {
} else if (result == NSOrderedDescending) {
}  else {
    //the same
}

Note, that in this code, date1 and date2 will be overwritten. Alternatively you can pass in a reference to another NSDate pointer for startDate as shown in the code above, where now stays untouched.

初与友歌 2024-11-21 00:47:51

我使用了另一种方法与 NSDateFormatter 和字符串比较,比
NSDate compare 方法,但编写速度更快,并且足够灵活,可以进行各种比较:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

if ([[dateFormat stringFromDate:date1] isEqualToString:[dateFormat stringFromDate:date2]])
{
    //It's the same day
}

I have used another method with NSDateFormatter and a string comparison, less smarter than
NSDate compare method but faster to write and flexible enough to do variety of comparison :

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];

if ([[dateFormat stringFromDate:date1] isEqualToString:[dateFormat stringFromDate:date2]])
{
    //It's the same day
}
罗罗贝儿 2024-11-21 00:47:51

好吧,距最初的问题提出已有几年了,但可能值得一提的是 NSCalendar 现在有许多方法可以使某些日期比较问题更加直接:

NSCalendar *currentCalendar = [NSCalendar currentCalendar];
Bool sameDay = [currentCalendar isDate:dateA inSameDayAsDate:dateB];

Okay, so it's a few years after the original question was asked, but it's probably worth mentioning that NSCalendar now has a number of methods that make certain date comparison questions much more straight-forward:

NSCalendar *currentCalendar = [NSCalendar currentCalendar];
Bool sameDay = [currentCalendar isDate:dateA inSameDayAsDate:dateB];
不忘初心 2024-11-21 00:47:51

Swift 版本,比较日期并忽略它们的时间。

let dateExam1:NSDate = NSDate.init(timeIntervalSinceNow: 300)
let dateExam2:NSDate = NSDate.init(timeIntervalSinceNow: 10000)

let currCalendar = NSCalendar.currentCalendar()

let dateCompanent1:NSDateComponents = currCalendar.components([.Year,.Month,.Day], fromDate: dateExam1)
let dateCompanent2:NSDateComponents = currCalendar.components([.Year,.Month,.Day], fromDate: dateExam2)

let date1WithoutTime:NSDate? = currCalendar .dateFromComponents(dateCompanent1)
let date2WithoutTime:NSDate? = currCalendar .dateFromComponents(dateCompanent2)
if (date1WithoutTime != nil) && (date2WithoutTime != nil)
{
    let dateCompResult:NSComparisonResult = date1WithoutTime!.compare(date2WithoutTime!)
    if (dateCompResult == NSComparisonResult.OrderedSame)
    {
        print("Same Dates")
    }
    else
    {
        print("Different Dates")
    }
}

Swift Version , Comparing Dates and ignoring their time.

let dateExam1:NSDate = NSDate.init(timeIntervalSinceNow: 300)
let dateExam2:NSDate = NSDate.init(timeIntervalSinceNow: 10000)

let currCalendar = NSCalendar.currentCalendar()

let dateCompanent1:NSDateComponents = currCalendar.components([.Year,.Month,.Day], fromDate: dateExam1)
let dateCompanent2:NSDateComponents = currCalendar.components([.Year,.Month,.Day], fromDate: dateExam2)

let date1WithoutTime:NSDate? = currCalendar .dateFromComponents(dateCompanent1)
let date2WithoutTime:NSDate? = currCalendar .dateFromComponents(dateCompanent2)
if (date1WithoutTime != nil) && (date2WithoutTime != nil)
{
    let dateCompResult:NSComparisonResult = date1WithoutTime!.compare(date2WithoutTime!)
    if (dateCompResult == NSComparisonResult.OrderedSame)
    {
        print("Same Dates")
    }
    else
    {
        print("Different Dates")
    }
}
绝影如岚 2024-11-21 00:47:51

快速更新@LuAndre 答案 5

    let dateExam1 = Date(timeIntervalSinceNow: 300)
    let dateExam2 = Date(timeIntervalSinceNow: 10000)

    let currCalendar = Calendar.current

    let dateCompanent1 = currCalendar.dateComponents([.year,.month,.day], from: dateExam1)
    let dateCompanent2 = currCalendar.dateComponents([.year,.month,.day], from: dateExam2)


    if  let date1WithoutTime = currCalendar.date(from:dateCompanent1), let dateCompanent2 = currCalendar.date(from:dateCompanent2) {
            let dateCompResult = date1WithoutTime.compare(dateCompanent2)
            if (dateCompResult == ComparisonResult.orderedSame)
            {
                print("Same Dates")
            }
            else
            {
                print("Different Dates")
            }
        
    }

Updating @LuAndre answer swift 5

    let dateExam1 = Date(timeIntervalSinceNow: 300)
    let dateExam2 = Date(timeIntervalSinceNow: 10000)

    let currCalendar = Calendar.current

    let dateCompanent1 = currCalendar.dateComponents([.year,.month,.day], from: dateExam1)
    let dateCompanent2 = currCalendar.dateComponents([.year,.month,.day], from: dateExam2)


    if  let date1WithoutTime = currCalendar.date(from:dateCompanent1), let dateCompanent2 = currCalendar.date(from:dateCompanent2) {
            let dateCompResult = date1WithoutTime.compare(dateCompanent2)
            if (dateCompResult == ComparisonResult.orderedSame)
            {
                print("Same Dates")
            }
            else
            {
                print("Different Dates")
            }
        
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文