根据开始时间和时差倒计时

把类似2017-09-08 12:33:10的字符串变为时间date

-(NSDate *)getDateWithString:(NSString *)dateString{

NSString* string = dateString;

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];

[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];

[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate* inputDate = [inputFormatter dateFromString:string];

return inputDate;

}

根据开始时间和时间差倒计时

-(NSString *)getTempTimeWithtimeinterval:(NSTimeInterval)time beginTime:(NSDate*)date{

//    NSDate * date = [NSDate date];

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

//设置时间间隔(秒)(这个我是计算出来的,不知道有没有简便的方法 )

//    NSTimeInterval time = 365 * 24 * 60 * 60;//一年的秒数

//得到一年之前的当前时间(-:表示向前的时间间隔(即去年),如果没有,则表示向后的时间间隔(即明年))

NSDate * lastYear = [date dateByAddingTimeInterval:-time];

//转化为字符串

NSString * startDate = [dateFormatter stringFromDate:lastYear];

return startDate;

}


举个例子:

/*

场景: 后台返回一个时间字符串 需要一段时间倒计时

我的思想是 用返回的时间字符串 减去 一个时间差 无论什么地区的时间 时间差一定是一样的

这个时间差 就是 请求数据的或者 收到数据的时候 把当前时间保存 然后 最新的当前时间与保存的当前时间 计算时间差

注意: yyyy-MM-dd HH:mm:ss 这个时间的格式 需要根据需求而定

*/

NSDate * newdata = [NSDate date]; //当前时间

//    NSLog(@"_locationDate == %@",_locationDate);

//_locationDate 为刚开始请求数据的时间

_timeInterval = [newdata timeIntervalSinceDate:_locationDate];// 计算刚开始请求数据与当前时间的时间差

NSString * timeString = @"2017-10-09 12:11:11"; //需要倒计时的起始时间

NSDate * begindate = [self getDateWithString:timeString]; //把起始时间转为date

NSString * endTime = [self getTempTimeWithtimeinterval:_timeInterval beginTime:begindate]; //输出起始时间减去时差的结果

你可能感兴趣的:(根据开始时间和时差倒计时)