iOS:比较两个日期

发布于 2024-11-09 02:42:43 字数 296 浏览 0 评论 0原文

我有一个 NSDate,我必须将其与其他两个 NSDate 进行比较,并且我尝试使用 NSOrderAscendingNSOrderDescending 但如果我的其他两个日期的日期相等吗?

示例:如果我有一个 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 技术交流群。

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

发布评论

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

评论(6

同尘 2024-11-16 02:42:43

根据 NSDate 比较的 Apple 文档:

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

- (NSComparisonResult)比较:(NSDate *)anotherDate

参数 anotherDate

用于比较的日期
接收者。该值不能为零。
如果该值为 nil,则行为为
未定义,将来可能会改变
Mac OS X 版本。

返回值

如果:

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

接收者稍后在
时间比另一个日期,
NSOrderedDescending

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

换句话说:

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

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

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

请参阅有关此的 Apple 文档

According to Apple documentation of NSDate compare:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

- (NSComparisonResult)compare:(NSDate *)anotherDate

Parameters anotherDate

The date with which to compare the
receiver. This value must not be nil.
If the value is nil, the behavior is
undefined and may change in future
versions of Mac OS X.

Return Value

If:

The receiver and anotherDate are
exactly equal to each other,
NSOrderedSame

The receiver is later in
time than anotherDate,
NSOrderedDescending

The receiver is
earlier in time than anotherDate,
NSOrderedAscending

In other words:

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

Note that it might be easier in your particular case to read and write this :

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

See Apple Documentation about this one.

忆梦 2024-11-16 02:42:43

经过搜索,我得出的结论是,最好的方法是这样的:

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
    NSDate* enddate = checkEndDate;
    NSDate* currentdate = [NSDate date];
    NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
    double secondsInMinute = 60;
    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

    if (secondsBetweenDates == 0)
        return YES;
    else if (secondsBetweenDates < 0)
        return YES;
    else
        return NO;
}

您也可以将其更改为小时之间的差异。


如果您只想比较 dd/MM/yyyy 格式的日期,则需要在 NSDate* currentdate = [NSDate date]; && 之间添加以下行NSTimeInterval距离

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];

After searching, I've got to conclusion that the best way of doing it is like this:

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
    NSDate* enddate = checkEndDate;
    NSDate* currentdate = [NSDate date];
    NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
    double secondsInMinute = 60;
    NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

    if (secondsBetweenDates == 0)
        return YES;
    else if (secondsBetweenDates < 0)
        return YES;
    else
        return NO;
}

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

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]
                          autorelease]];

NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];

currentdate = [dateFormatter dateFromString:stringDate];
多彩岁月 2024-11-16 02:42:43

我认为您是在问比较函数的返回值是什么。

如果日期相等,则返回 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

暮凉 2024-11-16 02:42:43

我不确切知道您是否问过这个问题,但如果您只想比较 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];
}

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:

- (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];
}
棒棒糖 2024-11-16 02:42:43

NSDate 实际上表示自参考日期(我认为 UTC 2000 年 1 月 1 日)以来的时间间隔(以秒为单位)。在内部,使用双精度浮点数,因此两个任意日期即使在同一天也不太可能比较相等。如果您想查看特定日期是否在特定日期,您可能需要使用NSDateComponents。例如

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.  
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 

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 use NSDateComponents. e.g.

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.  
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 
夜还是长夜 2024-11-16 02:42:43

检查以下日期比较函数,首先创建两个 NSDate 对象并传递给该函数:
在 viewDidload 中或根据您的场景添加以下代码行。

-(void)testDateComaparFunc{

NSString *getTokon_Time1 = @"2016-05-31 03:19:05 +0000";
NSString *getTokon_Time2 = @"2016-05-31 03:18:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}

这是函数

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    //"date1 is later than date2
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    //date1 is earlier than date2
    isTokonValid = NO;
} else {
   //dates are the same
    isTokonValid = NO;

}

return isTokonValid;}

只需更改日期并测试上面的函数:)

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.

-(void)testDateComaparFunc{

NSString *getTokon_Time1 = @"2016-05-31 03:19:05 +0000";
NSString *getTokon_Time2 = @"2016-05-31 03:18:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"];
NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}

here is the function

-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{

BOOL isTokonValid;

if ([date1 compare:date2] == NSOrderedDescending) {
    //"date1 is later than date2
    isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
    //date1 is earlier than date2
    isTokonValid = NO;
} else {
   //dates are the same
    isTokonValid = NO;

}

return isTokonValid;}

Simply change the date and test above function :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文