当我们获取短信验证码后,通常情况下,我们会写一个多少秒后重新获取,此时,如果我们不做任何处理,当程序进入后台(按“HOME”键),倒计时也会停止,当重新返回前台时,倒计时还是从原来进入后台的时间继续倒计时。
因此,我们需要在程序进入后台时,倒计时依旧可以进行,首先项目中要获取到时间戳里的毫秒单位:
/************************↓↓↓↓**DEMO**↓↓↓↓**************************/
主要代码:
-(void)dealloc
{
[selfremoveObserver];
[superdealloc];
}
//移除通知
-(void)removeObserver
{
[[NSNotificationCenterdefaultCenter]removeObserver:self];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [superinitWithCoder:aDecoder];
if (self) {
[selfaddObserver];
}
returnself;
}
//监听通知
-(void)addObserver
{
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleAppDidBackGround)name:UIApplicationDidEnterBackgroundNotificationobject:nil];
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(handleAppDidEnterForeground)name:UIApplicationWillEnterForegroundNotificationobject:nil];
}
//程序进入后台
-(void)handleAppDidBackGround
{
_backGroundInterval = (longlongint)[[NSDatedate]timeIntervalSince1970];//取当前时间戳
}
//程序进入前台
-(void)handleAppDidEnterForeground
{
longlongint foreInterval = (longlongint)[[NSDatedate]timeIntervalSince1970];//取当前时间戳
int differ = (int)( foreInterval -_backGroundInterval);
_timerNumber = (_timerNumber >=0)?(_timerNumber - differ):_timerNumber;
}
/************************↑↑↑↑**DEMO**↑↑↑↑***********************/
获取到当前时间戳方法:
long long int date = (long long int)time;
NSLog(@”date\n%d”, date); //1295322949
可转换为字符型:
NSString *timeString = [NSString stringWithFormat:@"%f", a];//转为字符型
如果你想格式化输出 可以:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss:SSS"];
NSString *date = [formatter stringFromDate:[NSDate date]];
NSString *timeLocal = [[NSString alloc] initWithFormat:@"%@",date];
NSLog(@"%@",timeLocal);
ios NSDate 时间戳 时间间隔