我想找到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
答案 0 :(得分:1)
我使用NSTimeZone
修复了我的问题。这是我的问题。它显示日期作为他们的服务器日期,我的当前日期与时区不匹配,无法格式化。感谢所有朋友帮助我找到错误。
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"EST"]; [dateFormatter setTimeZone:gmt];
答案 1 :(得分: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];