What is it you're actually trying to accomplish? To populate an NSDateComponents
with the time elapsed between two dates? In that case, you probably want -[NSCalendar components:fromDate:toDate:options:]
, with the from-date being your start, and the to-date being the current date when you stop. In the mean time, you seem to be doing a lot of complicated and possibly unnecessary mashing of dates together.
Getting unexpected output from NSDateComponents
Pregunta
After comparing two dates (currentDate
and _timerStartDate
) I get the following output
nstimeinterval: 88.998212
2014-05-14 14:07:08.284 currentDate: 14-05-2014 14:07:08
2014-05-14 14:07:08.284 stopDate: 14-05-2014 14:05:39
2014-05-14 14:07:08.284 hour: 10
This is correct and expected. However when I break timerDate
down I get 10 hours from the NSLog...I'm expecting zero. What am I doing wrong?
Here is my code:
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:_timerStartDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"mm:ss"];
NSString *timeString=[dateFormatter stringFromDate:timerDate];
NSLog(@"nstimeinterval: %f", timeInterval);
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
NSLog(@"currentDate: %@", [dateFormatter stringFromDate:currentDate]);
NSLog(@"stopDate: %@", [dateFormatter stringFromDate:_timerStartDate]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: ( NSHourCalendarUnit | NSYearCalendarUnit) fromDate:timerDate];
NSLog(@"year: %li", (long)components.year);
NSLog(@"timer: %@", timeString);
timerTicksForCounter = timeString;
NSLog(@"hour: %li", (long)components.hour);
Solución
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow