iOS开发之计算两个日期的时间间隔
//首先创建格式化对象
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//然后创建日期对象
NSDate *date1 = [dateFormatter dateFromString:@"2020-10-31 00:00:00"];
NSDate *date = [NSDate date];
//计算时间间隔(单位是秒)
NSTimeInterval time = [date1 timeIntervalSinceDate:date];
//计算天数、时、分、秒
int days = ((int)time)/(3600*24);
int hours = ((int)time)%(3600*24)/3600;
int minutes = ((int)time)%(3600*24)%3600/60;
int seconds = ((int)time)%(3600*24)%3600%60;
NSString *dateContent = [[NSString alloc] initWithFormat:@"仅剩%i天%i小时%i分%i秒",days,hours,minutes,seconds];
(%i可以自动将输入转换为十进制,而%d则不会进行转换)
//赋值显示
UILabel *timeLab = (UILabel *)[self.view viewWithTag:666666];
timeLab.text = dateContent;