0

这是设置,我有一个我正在使用的 JSON 提要,我想找出两个名为posted_date和的特定日期之间的差异planned_expiration_date。它们的格式很奇怪,所以我想我可以将它们截断为日期。然后我可以用它NSTimeInterval来找出以秒为单位的差异。

// Time Interval Left
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSString *startDate = [firstPerson objectForKey:@"posted_date"];
NSString *endDate = [firstPerson objectForKey:@"planned_expiration_date"];

//Ammend the strings to YYYY-MM-DD
[formatter setDateFormat:@"yyyy-mm-dd"];
int newlength = 9;
NSDate *startDateAmmended =[formatter dateFromString:[startDate substringFromIndex:newlength]];
NSDate *endDateAmmended = [formatter dateFromString:[endDate substringFromIndex:newlength]];

这是我不太确定的一点。日期"2013-06-07T13:40:01Z"直接从提要中显示出来。我不知道如何处理日期格式化程序方法中的 T 和 Z 字符,因此我将字符串截断为substringFromIndex10 个字符,然后尝试以下代码。

//Difference in Date
NSTimeInterval *startDifference = [startDateAmmended timeIntervalSinceNow];
NSTimeInterval *endDifference = [endDateAmmended timeIntervalSinceNow];

NSTimeInterval timeDifferenceInSeconds = startDifference - endDifference;

在前.../JSONParser/ViewController.m:52:21: Initializing 'NSTimeInterval *' (aka 'double *') with an expression of incompatible type 'NSTimeInterval' (aka 'double')两次调用NSTimeInterval.

我确信我在一些地方出错了,而且我确信这不是最简单的方法。谁能推荐我将如何解决这个问题或更简单的方法来获取日期之间的差异?

4

2 回答 2

2

您的错误来自您的行:

NSTimeInterval *startDifference = [startDateAmmended timeIntervalSinceNow];
NSTimeInterval *endDifference = [endDateAmmended timeIntervalSinceNow];

他们应该是:

NSTimeInterval startDifference = [startDateAmmended timeIntervalSinceNow];
NSTimeInterval endDifference = [endDateAmmended timeIntervalSinceNow];

或者,更简单地说,根本不定义这两个差异变量,只需使用:

NSTimeInterval timeDifferenceInSeconds = [endDateAmmended timeIntervalSinceDate:startDateAmmended];

要计算两个ISO 8601 / RFC 3339日期字符串之间的差异,您可以执行以下操作:

NSDate *startDate = [self dateFromISO8601String:@"2013-06-01T16:27:35Z"];
NSDate *endDate   = [self dateFromISO8601String:@"2013-06-07T13:40:01Z"];

NSTimeInterval elapsed = [endDate timeIntervalSinceDate:startDate];
NSLog(@"Time elapsed (in seconds) is %.0f", elapsed);

其中dateFromISO8601String定义为:

- (NSDate *)dateFromISO8601String:(NSString *)string
{
    static NSDateFormatter *formatter = nil;
    if (formatter == nil)
    {
        formatter = [[NSDateFormatter alloc] init];
        NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        formatter.locale = enUSPOSIXLocale;
        formatter.dateFormat = @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
        formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    }
    return [formatter dateFromString:string];
}
于 2013-06-07T15:19:35.220 回答
1

NSDate您可以像这样获得两个对象之间的秒数差异:

double difference = [startDateAmmended timeIntervalSinceDate:endDateAmmended];

请注意,使用子字符串操作您没有时间,只有日期,因此difference将以秒为单位,但步骤为一整天。

于 2013-06-07T15:08:35.070 回答