格式化日期问题

时间:2013-06-07 15:03:58

标签: objective-c nsdate nstimeinterval

以下是设置,我使用的是JSON Feed,我希望找到名为posted_dateplanned_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]];

这是我不太确定的一点。日期在Feed中直接显示为此"2013-06-07T13:40:01Z"。我不知道如何处理日期格式化程序方法中的T和Z字符,所以我用substringFromIndex截断字符串使其成为10个字符,然后尝试以下代码。

//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

我确信我在一些地方出错了,我确信这不是最简单的方法。任何人都可以推荐我如何解决这个问题或者更简单的方法来获取日期之间的差异?

2 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:1)

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

double difference = [startDateAmmended timeIntervalSinceDate:endDateAmmended];

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