如何使用此inBetweenDate消息?

时间:2010-10-18 05:26:31

标签: iphone objective-c xcode

我是iphone编程的新手。我需要一些关于此代码的帮助。

我在这里找到了我需要的东西 - How to Check if an NSDate occurs between two other NSDates

但我不知道如何使用这段代码。

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;

    if ([date compare:endDate] == NSOrderedDescending) 
        return NO;

    return YES;
}

我需要有关如何使用此功能的帮助。

我创建了NSDATE + Helper.h和NSDATE + Helper.m

我的NSDATE + Helper.h

#import <Foundation/Foundation.h>


@interface NSDATEHelper : NSDate {

}

@end

的NSDate + Helper.m

#import "NSDATE+Helper.h"


@implementation NSDATE (Helper)

+ (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate
{
    if ([date compare:beginDate] == NSOrderedAscending)
        return NO;

    if ([date compare:endDate] == NSOrderedDescending) 
        return NO;

    return YES;
}

这不起作用。我收到了一些错误。你能帮忙解决这个问题。

2 个答案:

答案 0 :(得分:1)

此代码采用NSDate并告诉您它是否在两个其他日期之间:

NSDate * queryDate = [NSDate date];
NSDate * startDate= [NSDate date];
NSDate * endDate = [NSDate date];

// is query date between startDate and endDate
if ([NSDate date:queryDate isBetweenDate:startDate andDate:endDate])

您正在通过extending NSDate添加此静态消息,因此您需要定义以下内容:

@interface NSDate (Helper)
    + (BOOL)date:(NSDate*)date isBetweenDate:(NSDate*)beginDate andDate:(NSDate*)endDate;
@end

在NSDate + Helper.h和NSDate + Helper.m中实现。

答案 1 :(得分:0)

我为此写了一个新方法。

- (BOOL) isBetweenDate:(NSString *)str1 andDate:(NSString *)str2 {
    NSDateFormatter * dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *Date = [dateFormat dateFromString:datestr];
    NSDate * Date1 = [dateFormat dateFromString:str1];
    NSDate * Date2 = [dateFormat dateFromString:str2];
    NSComparisonResult comparison1 = [Date compare:Date1];
    NSComparisonResult comparison2 = [Date compare:Date2];
    if((comparison1 == NSOrderedSame || comparison1 == NSOrderedDescending) && (comparison2==NSOrderedSame || comparison2 == NSOrderedAscending))
    {
        return YES;
    }
    return NO;
}

我发现很难用另一种方式。谢谢你的帮助。