0

我正在尝试查找 2 个日期之间的时差。但我得到的值为-0.0000,nan-357683564. 下面是我查找时差的代码。我在这个计算中做错了吗?

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.timeStyle = NSDateFormatterNoStyle;
formatter.dateFormat = @"YYYY-MM-dd HH:MM:SS ±HHMM";//MM/dd/yyyy
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale:usLocale];
NSDate *intialTime= [formatter dateFromString:[NSString stringWithFormat:@"%@",[dateArray objectAtIndex:i]]];//[formatter dateFromString:@"12/11/2005"];
NSDate *presentDate = [NSDate date];
NSTimeInterval timeInterval = [presentDate timeIntervalSinceDate:intialTime];
int seconds = (int)ceil(timeInterval);
int mins = seconds / 60;
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = timeInterval / secondsInAnHour;
NSLog(@"Time interval in Mins:%d -- %.4f -- %d",mins,timeInterval,hoursBetweenDates);

在日志中:

Time interval in Mins:-35791394 -- nan -- -2147483648

intialTime - (null) and presentDate - 2014-05-09 10:30:15 +0000

4

2 回答 2

1

我使用NSTimeZone. 这是我的问题。它将日期显示为他们的服务器日期,而我的当前日期与时区不匹配,无法格式化。感谢所有朋友帮助我找到我的错误。

    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
    [dateFormatter setTimeZone:gmt];
于 2014-05-10T13:13:48.020 回答
0
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];

    NSDate *dateToday = [NSDate date];

    NSString *date = @"09-05-14";   // Put your initial date here...

    [df setDateFormat:@"HH:mm:ss"];
    NSString *todayString = [df stringFromDate:[NSDate date]];
    NSString *todaysDateTime = [date stringByAppendingString:todayString];

    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *initialDate = [df dateFromString:todaysDateTime];

    NSTimeInterval ti = [initialDate timeIntervalSinceDate:dateToday];
于 2014-05-09T11:42:18.057 回答