NSDate 无法正常工作

NSDate not working properly

我想每秒获取一次电流,但是当我实现这个概念时,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);
}];

我的输出是,时间也不对。

我认为您尝试设置日期格式时有误:

[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

也许这个网站可以帮助您设置 dateFormathttp://nsdateformatter.com

当您设置以下格式时(小 mmss):

[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