NSDate 比较总是 returns NSOrderedAscending
NSDate compare always returns NSOrderedAscending
我正在检查给定日期和时间是否已经超过当前日期和时间。这是我所做的
NSString *End = [[values objectAtIndex:index]valueForKey:@"EndTime"];
fmt.dateFormat = @"yyyy-MM-dd hh:mm:ss";
utc = [fmt dateFromString:End];
NSDate *endDateInLocalTimezone = [utc dateByAddingTimeInterval:timeZoneSeconds];
fmt.dateFormat = @"MMMM dd, hh:mm a";
endDateInLocalTimezone = [fmt stringFromDate:endDateInLocalTimezone];
NSDate *now = [NSDate date];
now = [fmt stringFromDate:now];
if([endDateInLocalTimezone compare:now] == NSOrderedAscending)
{
index++;
continue;
}
我收到了 7 月 3 日 5:29 下午 endDateInLocalTimezone 并将其与我的 now 即 6 月 30 日 12:18 下午 。它仍然说在 NSOrderedAscending 中,这意味着左操作数小于右操作数。但在给定的情况下,右操作数小于左操作数。为什么它仍然在 if 中?
您比较的是日期对象的字符串再现,而不是日期对象本身。比较日期,而不是字符串。
例如:
NSString *dateString = values[index][@"EndTime"];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; // the EndTime is in GMT/UTC, tell you formatter that
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; // you generally should make sure to use `en_US_POSIX` in case user is not using gregorian calendar
NSDate *date = [fmt dateFromString:dateString];
NSDate *now = [NSDate date];
if ([date compare:now] == NSOrderedAscending) {
...
}
我正在检查给定日期和时间是否已经超过当前日期和时间。这是我所做的
NSString *End = [[values objectAtIndex:index]valueForKey:@"EndTime"];
fmt.dateFormat = @"yyyy-MM-dd hh:mm:ss";
utc = [fmt dateFromString:End];
NSDate *endDateInLocalTimezone = [utc dateByAddingTimeInterval:timeZoneSeconds];
fmt.dateFormat = @"MMMM dd, hh:mm a";
endDateInLocalTimezone = [fmt stringFromDate:endDateInLocalTimezone];
NSDate *now = [NSDate date];
now = [fmt stringFromDate:now];
if([endDateInLocalTimezone compare:now] == NSOrderedAscending)
{
index++;
continue;
}
我收到了 7 月 3 日 5:29 下午 endDateInLocalTimezone 并将其与我的 now 即 6 月 30 日 12:18 下午 。它仍然说在 NSOrderedAscending 中,这意味着左操作数小于右操作数。但在给定的情况下,右操作数小于左操作数。为什么它仍然在 if 中?
您比较的是日期对象的字符串再现,而不是日期对象本身。比较日期,而不是字符串。
例如:
NSString *dateString = values[index][@"EndTime"];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; // the EndTime is in GMT/UTC, tell you formatter that
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]; // you generally should make sure to use `en_US_POSIX` in case user is not using gregorian calendar
NSDate *date = [fmt dateFromString:dateString];
NSDate *now = [NSDate date];
if ([date compare:now] == NSOrderedAscending) {
...
}