在iPhone中检查日期是否在两天之间 [英] Check if a date is between two days in iPhone

查看:114
本文介绍了在iPhone中检查日期是否在两天之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何比较日期。在我的情况下,让Date1 = 2011-10-14& Date2 = 2011-10-20。我想检查10月15日是否在Date1和Date2之间。为此,我使用以下代码:

I know how to compare dates.In my case, let Date1 = 2011-10-14 & Date2 =2011-10-20 .And I want to check if 15th Oct lie between Date1 and Date2.I'm using following codes for this:

if ( [date compare:Date1] == NSOrderedDescending && [date compare:Date2] == NSOrderedAscending) {   
            //write codes

        }

但这不会检查10月15日是否位于10月14日至20日之间,而是检查整个日期。因此,我将如何实现这一目标。
提前Thnx。

But this will not check if 15th oct lie between 14th and 20th Oct.rather it check for whole date. So, How will I implement this. Thnx in advance.

推荐答案

我希望以下代码对您有所帮助。假设您拥有Date1和Date2,

I hope the following code would help you. Assuming Date1 and Date2 you have,

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


NSDateComponents *firstComponents = [calendar components:desiredComponents fromDate:Date1];
NSDateComponents *secondComponents = [calendar components:desiredComponents fromDate:Date2];

NSDate *firstWOYear = [calendar dateFromComponents:firstComponents];
NSDate *SecondWOYear = [calendar dateFromComponents:secondComponents];

NSComparisonResult result = [firstWOYear compare:SecondWOYear];
if (result == NSOrderedAscending) {
    //Date1 is before Date2
} else if (result == NSOrderedDescending) {
    //Date1 is after Date2
}  else {
    //Date1 is the same day/month as Date2
}

这篇关于在iPhone中检查日期是否在两天之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆