我希望每秒都获得当前但是当我实现这个概念时,NSTimer的时间没有变化,我的代码是
[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer *timer){
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setDateFormat:@"YYYY-MM-DD HH:MM:SS"];
NSDate *date = [NSDate date];
NSString *dateTime = [formatter stringFromDate:date];
NSLog(@"Date and Time :%@",dateTime);
}];
答案 0 :(得分:2)
我认为当您尝试使用以下日期设置日期格式时出现错误:
[formatter setDateFormat:@"YYYY-MM-DD HH:MM:SS"];
我尝试过:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone localTimeZone]];
[formatter setDateStyle:NSDateFormatterMediumStyle];
[formatter setTimeStyle:NSDateFormatterFullStyle];
我的输出是:
Date and Time :Jan 27, 2017, 8:05:50 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:51 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:52 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:53 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:54 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:55 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:56 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:57 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:58 PM Central European Standard Time
Date and Time :Jan 27, 2017, 8:05:59 PM Central European Standard Time
也许这个网站可以帮助您设置dateFormat
:http://nsdateformatter.com
设置以下格式(小mm
和ss
)时:
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
你看到正确的分钟和秒
Date and Time :2017-01-27 20:10:18
Date and Time :2017-01-27 20:10:19
Date and Time :2017-01-27 20:10:20
Date and Time :2017-01-27 20:10:21
Date and Time :2017-01-27 20:10:22