#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) NSTimer *timer;
@end
@implementation ViewController
- (UILabel *)titleLabel
{
if (!_titleLabel) {
self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
_titleLabel.center = self.view.center;
_titleLabel.backgroundColor = [UIColor orangeColor];
_titleLabel.font = [UIFont systemFontOfSize:17.0];
_titleLabel.textColor = [UIColor whiteColor];
[self.view addSubview:_titleLabel];
}
return _titleLabel;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
//将timer添加到运行循环,模式:NSRunLoopCommonModes监听滚动模式
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
//获取到到期的时间,还需要转化一个取得时分秒.
- (NSString *)getCurrentTime
{
NSString *date = @"2015-04-16 11:54:50";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:date];
NSString *dateTime = [formatter stringFromDate:[NSDate date]];
return dateTime;
}
- (void)updateTimer
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date1 = [formatter dateFromString:[self getCurrentTime]];
NSDate *date2 = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date2];
NSDate *localeDate = [date2 dateByAddingTimeInterval: interval];
NSTimeInterval aTimer = [localeDate timeIntervalSinceDate:date1];
//aTimer为负的 aTimer1把aTimer转为正的
NSTimeInterval aTimer1 = - aTimer;
NSInteger day = (NSInteger)(aTimer1/(3600*24));
NSInteger hour = (NSInteger)(aTimer1/3600);
NSInteger minute = (NSInteger)(aTimer1 - hour*3600)/60;
NSInteger second = (aTimer1 - hour*3600 - minute*60);
NSLog(@" %f %ld %ld %ld",aTimer1, hour,minute,second);
if (hour >= 24) {
hour %= 24;
}
NSLog(@" %f %ld %ld %ld",aTimer1, hour,minute,second);
NSString *dural = [NSString stringWithFormat:@"%ld天%ld时%ld分%ld秒", day,hour, minute,second];
if (hour <= 0 && minute <= 0 && second <= 0) {
self.titleLabel.text = @"活动已过期,谢谢关注";
[self pause];
} else {
self.titleLabel.text = dural;
}
}
- (void)pause
{
//停止时钟,invalidate是唯一的方法,一调用就干掉timer了,想再用只能重新实例化
[self.timer invalidate];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
iOS倒计时
最新推荐文章于 2022-03-21 10:25:12 发布