1

我对这段代码有疑问:

+ (NSDate *)dateByMovingToBeginningOfDay:(NSDate *)date
{
    unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents* parts = [[NSCalendar currentCalendar] components:flags fromDate:date];
    [parts setHour:0];
    [parts setMinute:0];
    [parts setSecond:0];

    return [[NSCalendar currentCalendar] dateFromComponents:parts];
}

+ (NSDate *)dateByMovingToEndOfDay:(NSDate *)date
{
    unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents *parts = [[NSCalendar currentCalendar] components:flags fromDate:date];
    [parts setHour:23];
    [parts setMinute:59];
    [parts setSecond:59];

    return [[NSCalendar currentCalendar] dateFromComponents:parts];
}

+ (BOOL)checkForReportInDate:(NSDate *)date forUser:(User *)user
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext *context = appDelegate.managedObjectContext;

    NSDate *startDate = [NSDate dateByMovingToBeginningOfDay:date];
    NSDate *endDate = [NSDate dateByMovingToEndOfDay:date];

    NSLog(@"apply date: %@", date.description);
    NSLog(@"start date: %@", startDate.description);
    NSLog(@"end date: %@", endDate.description);

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    fetchRequest.entity = [NSEntityDescription entityForName:@"Report" inManagedObjectContext:context];
    fetchRequest.predicate = [NSPredicate predicateWithFormat:@"user == %@ AND (date > %@ AND date < %@)", user, startDate, endDate];
    fetchRequest.fetchLimit = 1;

    NSError *error = nil;

    NSUInteger reportExist = [context countForFetchRequest:fetchRequest error:&error];

    if(error != nil) {
        NSLog(@"Error: %@", [error localizedDescription]);
        return NO;
    }

    if(reportExist > 0) {
        return 1;
    }
    else {
        return 0;
    }
}

它生成错误的开始日期......在我的控制台中我有

2012-04-12 14:34:46.456 iFood Pro[23820:fb03] 将报告保存到数据库 2012-04-12 14:34:46.458 iFood Pro[23820:fb03] 申请日期:2012-04-12 12:34: 41 +0000 2012-04-12 14:34:46.458 iFood Pro[23820:fb03] 开始日期:2012-04-11 22:00:00 +0000 2012-04-12 14:34:46.459 iFood Pro[23820: fb03]结束日期:2012-04-12 21:59:59 +0000

开始日期应该是 2012-04-12 00:00:00 +0000 而不是 2012-04-11 22:00:00 +0000 为什么会出现这种行为?我快疯了!

4

1 回答 1

1

已修复,问题出在时区...using [parts setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];解决了问题

于 2012-04-15T12:47:03.117 回答