如何设置NSDate时间的日期部分以比较时间?

时间:2013-07-25 16:18:17

标签: ios nsdate nsdatecomponents

我从网络服务获得NSStrings上午7:00和下午10:00。我使用此代码块将它们转换为NSDate:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"hh:mm a"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];

    NSString *openDateString = (NSString*)[timeStringsArray2 objectAtIndex:0];
    NSString *closeDateString = (NSString*)[timeStringsArray2 objectAtIndex:1];

    NSDate *openDate = [dateFormatter dateFromString:openDateString];
    NSDate *closeDate = [dateFormatter dateFromString:closeDateString];

if ([self timeCompare:openDate until:closeDate]) {
        NSLog(@"OPEN-timeCompare");
    } else {
        NSLog(@"CLOSED-timeCompare");
    }

这是比较方法:

-(BOOL)timeCompare:(NSDate*)date1 until:(NSDate*)date2{
    NSDate *date = [NSDate date];
    NSLog(@"open:%@ now:%@ close:%@", date1, date, date2);
    return ([date1 compare:date] == NSOrderedAscending && [date2 compare:date] == NSOrderedDescending);
}

所以当我比较这些值时,我正在比较:

  

开启时间:2013-07-26 12:00:00 +0000
  现在:2013-07-27 03:50:30 +0000   close:2013-07-27 03:00:00 +0000   CLOSED-timeCompare

我不知道为什么,因为现在它实际上是晚上10点到晚上10点之前的950点。它不应该等于过去关闭时间的时间,即使它是在UTC中。

2 个答案:

答案 0 :(得分:1)

使用NSDate比较选择器:

if ([date1 compare:date2]==NSOrderedDescending) {
   // date1 is after date2
}

还有earlyDate,timeIntervalSinceDate等。

更新: 例如,现在测试是在两个日期之间:

    NSDate *now = [NSDate date];
    if ([date1 compare:now]==NSOrderedAscending && [date2 compare:now]==NSOrderedDescending) {
        // now is between the 2 dates
    }

答案 1 :(得分:1)

NSDateFormatter默认为2000年没有提供年份。如果您希望openDate和closeDate在0001而不是2000年,请尝试:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Add year to expected date format
[dateFormatter setDateFormat:@"yyyy hh:mm a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CST"]];

NSString *openDateString = (NSString*)[timeStringsArray2 objectAtIndex:0];
NSString *closeDateString = (NSString*)[timeStringsArray2 objectAtIndex:1];

//make new strings with year 0001 + original time
NSString *adjustedOpenDateString = [NSString stringWithFormat:@"%@ %@", @"0001", openDateString];
NSString *adjustedCloseDateString = [NSString stringWithFormat:@"%@ %@", @"0001", closeDateString];

NSDate *openDate = [dateFormatter dateFromString:adjustedOpenDateString];
NSDate *closeDate = [dateFormatter dateFromString:adjustedCloseDateString];

这应该将日期格式化程序设置为查找一年,并将年份0001添加到您创建日期的字符串中。不幸的是,我现在远离Xcode,所以我无法保证没有拼写错误!