iOS:NSPredicate使用NSDate进行比较

我有一个名为startDate的NSDate属性存储在持久性存储中,格式如下(下图).

426174354 = 2014年7月4日

我需要使用谓词创建(3)NSFetchRequest.

对于startDate:

> fetchRequest1使用谓词需要根据用户的设备时间获取今天日期中的所有内容.
使用谓词的fetchRequest2需要根据用户的设备时间来获取过去的所有内容,这意味着昨天和之前的内容.
使用谓词的fetchRequest3需要获取将来的所有内容,这意味着基于用户设备时间的明天和之后的开始.

以下是我到目前为止的代码:

-(NSMutableArray *)getFetchPredicate:(NSUInteger)fetchRequestType
{
    NSDate *now = [self getcurrentTime:[NSDate date]];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    format.dateFormat = @"dd-MM-yyyy";
    format.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    NSString *stringDate = [format stringFromDate:now];
    NSDate *todaysDate = [format dateFromString:stringDate];
    //today's date is now a date without time. 

    NSMutableArray *subpredicates;

    if (fetchRequestType == 1)
    {
        NSPredicate *subPredToday = [NSPredicate predicateWithFormat:@"startDate == %@ ",todaysDate];
        [subpredicates addObject:subPredToday];
    }
    else if (fetchRequestType == 2)
    {
        NSPredicate *subPredPast = [NSPredicate predicateWithFormat:@"startDate < %@",todaysDate];
        [subpredicates addObject:subPredPast];
    }
    else if (fetchRequestType == 3)
    {
        NSPredicate *subPredFuture = [NSPredicate predicateWithFormat:@"startDate > %@",todaysDate];
        [subpredicates addObject:subPredFuture];
    }
    return subPredicates;
}

-(NSDate *)getcurrentTime:(NSDate*)date
{
    NSDate *sourceDate = date;

    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

    NSDate* deviceDateWithTime = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];
    return deviceDateWithTime;
}

上面的代码没有从CoreData获取正确的对象.我有一种感觉我的谓词比较是不正确的.我不知道如何将startDate中的存储时间转换为仅日期格式,并将其应用于Predicates进行比较.有什么建议么?

解决方法

我认为你今天的看法有问题. AFAIK,NSDate代表了一个绝对的时间点,所以你在没有“时间”的情况下创建“日期”的努力似乎是徒劳的.而且使用NSDateFormatter设置日期也是不稳定的.

我想你必须创建两个不同的NSDate对象:startOfCurrentDay(例如00:00:00)和endOfCurrentDay(例如23:59:59),并且亲自地使用NSCalendar.如果这样做,您的提取请求谓词将是:

if (fetchRequestType == 1)
    {
        NSPredicate *subPredToday = [NSPredicate predicateWithFormat:@"(startDate >= %@) AND (startDate <= %@)",startOfCurrentDay,endOfCurrentDay];
    }
    else if (fetchRequestType == 2)
    {
        NSPredicate *subPredPast = [NSPredicate predicateWithFormat:@"startDate < %@",startOfCurrentDay];
    }
    else if (fetchRequestType == 3)
    {
        NSPredicate *subPredFuture = [NSPredicate predicateWithFormat:@"startDate > %@",endOfCurrentDay];
    }

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...