我正在创建一个简单的计时器,但未能得到我所追求的结果日期。
我的问题是我从我的NSTimeInterval(最后的nslog)得到-34481.274523,而我想要从当前日期(currentDate
)开始的秒数。 stopDate
始终是currentDate
之前的日期。
下面的代码片段每秒都会从nstimer中调用。而不是简单地增加一个int我使用日期,因为它更容易执行其他日期相关的计算和格式显示。
这是我的代码:
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:stopDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
NSLog(@"nstimeinterval: %f", timeInterval);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: ( NSHourCalendarUnit | NSYearCalendarUnit) fromDate:timerDate];
NSLog(@"year: %li", (long)components.year);
if (components.year == 2000) {
timeString = @"00:00";
return;
}
NSLog(@"timer: %@", timeString);
timerTicksForCounter = timeString;
NSLog(@"hour: %li", (long)components.hour);
//Used to update uilabel
[self updateTimerLabel];
if (components.year < 2000) {
return;
}
if (components.hour == 0) {
..... I'm doing a bunch of stuff here