2013-02-15 57 views
1

我一直在研究一个应用程序,我将秒表集成到一个应用程序中。我有秒表正常工作,并显示秒/分钟等。
NSDate增加了一天

但我的问题是,我要当任务已经完成,以显示完整的时间

但每当(您可以在1天,2小时,3分4秒等完成了这个任务)我做它,它总是增加1天的等式(例如它应该是0天,0小时,2分14秒),但它输出1天,0小时,2分14秒。

代码:

startDate = [[NSDate date] retain]; 
NSDate *currentDate = [NSDate date]; 
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate]; 
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"D' Days, 'H' Hours, 'm' Minutes and 's' Seconds'"]; 
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]]; 
NSString *timeString = [dateFormatter stringFromDate:timerDate]; 
overtext2.text = timeString; 
[dateFormatter release]; 
+2

为什么你需要计时器的时间间隔,然后将其添加到1/1/1970? – bdesham 2013-02-15 15:48:37

回答

2

它看起来像你真的滥用的NSDate这里。

您得到“额外”日的原因是您实际上正在打印日期和时间,就好像您的计时器从1970年1月1日00:00:00开始。所以如果你的计时器运行4小时30分钟,timerDate将是04:30:00 1/1/1970。如果您的计时器要运行40天,那么这些日期将会结束,timerDate将是00:00:00 9/2/1970,您的“天数”值将为9,而不是预期的40。

你会更好手动计算天数,小时,分钟,秒:

NSDate *startDate; // When the timer was started 
NSTimeInterval timerValue = [[NSDate date] timeIntervalSinceDate:startDate]; // Time in seconds from startDate to now 
NSInteger secs = timerValue % 60; 
NSInteger mins = (timerValue % 3600)/60; 
NSInteger hours = (timerValue % 86400)/3600; 
NSInteger days = timerValue/86400; 
NSString *timeString = [NSString stringWithFormat:@"%d days, %d hours, %d minutes and %d seconds.", days, hours, mins, secs]; 
+0

谢谢,我将如何将其整合到我现在的代码中? – 2013-02-15 15:48:25

+0

那么你如何存储秒表的价值? – colincameron 2013-02-15 15:49:22

+0

startDate是我用来存储秒表开始日期的NSDate – 2013-02-15 15:55:22

0
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval]; 

这将增加的秒数到1970年,然后要转换到时候天:小时:分钟:秒,即永远不会发生。

或者你可以做:

NSInteger seconds=timeInterval;//timeInterval float converted to long. 
NSInteger secs = seconds% 60; 
NSInteger mins = (seconds% 3600)/60; 
NSInteger hours = (seconds% 86400)/3600; 
NSInteger days = seconds/ 86400; 
NSString *timeString = [NSString stringWithFormat:@"%d days, %d hours, %d minutes and %d seconds.", days, hours, mins, secs]; 
+0

任何提示?我不是很熟悉这个NSDate的东西 – 2013-02-15 15:41:07

+0

然后看看NSDateFormattingGuide – AlexWien 2013-02-15 15:47:07

+0

@SimonAndersson:检查我的答案。 – 2013-02-15 15:57:51

0

你听说过日期时间除了..? 曾经造成我遇到过的其中一种情况的问题。所以我建议你在添加或减少日期时总是使用NSDateComponents。这是做了正确的方式..请与尝试一下,看看它是否工作..

0

答案就在于,这是问题

d 1..2 1日的文件中 - 日月 D 1..3 345每年的日期

在你的情况下,你计算的间隔有秒,但是一天是一年中的第一天。

如果您修改代码如下所示包含月份,您还将获得1(1月份)。

[dateFormatter setDateFormat:@"D' Days, 'M' Months, 'H' Hours, 'm' Minutes and 's' Seconds'"];