iOS) 当我接近秒级别时,timeIntervalSince70 的值是固定的

iOS) value of timeIntervalSince70 is fixed when i approach at the level of second

我想更新显示每秒 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 会产生问题?有什么解决办法吗?

使用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);

我认为你应该使用 NSDateComponents 来获取两天之间 days/hours/minutes/seconds 的数量。

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

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));

计算 diff_sec 时出错,除以 60 不正确,因为 diff 已经以秒为单位。

代码不正确:

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

正确的代码

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