当我接近第二级时,iOS)timeIntervalSince70的值是固定的

时间:2015-04-14 12:24:36

标签: ios timer nsdate

我想更新标签,显示每秒2 nsdates之间剩余的时间。

我的代码如下:

NSDate *nowDate = [NSDate date];
double diff = [campaignDate timeIntervalSince1970] - [nowDate timeIntervalSince1970];

int diff_day = diff/60/60/24 - 1; 
int diff_hour = ((int)diff/60/60)%24;
int diff_min = ((int)diff/60)%60;
int diff_sec = ((int)diff/60/60)%60;

当我记录diff_sec时,它总是显示49 日,小时和分钟值按工作顺序打印

为什么diff_sec会出问题?有什么解决方案吗?

3 个答案:

答案 0 :(得分:3)

我认为您应该使用NSDateComponents来获取两天之间的天数/小时/分钟/秒。

然后你可以得到这样的剩余时间:

NSDate *fromDate = [NSDate date];
NSDate *toDate = [NSDate dateWithTimeIntervalSinceNow:12345];

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *difference = [calendar components:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:fromDate toDate:toDate options:0];

NSLog(@"Event in %@ days, %@:%@:%@", @(difference.day), @(difference.hour), @(difference.minute), @(difference.second));

答案 1 :(得分:0)

使用NSCalendar

NSDate *dateA;
NSDate *dateB;

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                           fromDate:dateA
                                             toDate:dateB
                                            options:0];

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);

答案 2 :(得分:0)

错误在于计算diff_sec,除以60是不正确的,因为diff已经是几秒钟了。

代码不正确:

int diff_sec = ((int)diff/60/60)%60;

更正代码

int diff_sec = ((int)diff)%60;