Cocoa touch NSDate增加一天

Cocoa touch NSDate增加一天,cocoa-touch,Cocoa Touch,我一直在开发一款应用程序,将秒表集成到其中。我让秒表正常工作,并正确显示秒/分钟等。 但我的问题是,我想显示任务完成时的完整时间(您在1天、2小时、3分钟、4秒等时间内完成此任务) 但每当我这样做时,它总是在等式中加上1天(例如,它应该是0天、0小时、2分钟和14秒),但它输出1天、0小时、2分钟和14秒 代码: 这会将秒数增加到1970,然后将该时间转换为天:小时:分钟:秒,这永远不会发生 或者,您可以执行以下操作: NSInteger seconds=timeInterval;//timeI

我一直在开发一款应用程序,将秒表集成到其中。我让秒表正常工作,并正确显示秒/分钟等。

但我的问题是,我想显示任务完成时的完整时间(您在1天、2小时、3分钟、4秒等时间内完成此任务)

但每当我这样做时,它总是在等式中加上1天(例如,它应该是0天、0小时、2分钟和14秒),但它输出1天、0小时、2分钟和14秒

代码:

这会将秒数增加到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];

看起来你真的在滥用NSDate

您获得“额外”一天的原因是您实际上正在打印日期和时间,就好像您的计时器是在1970年1月1日00:00:00启动的一样。因此,如果计时器运行4小时30分钟,
timerDate
将为1970年1月1日04:30:00。如果您的计时器将运行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];

你听说过日期时间加法吗。。?
在我做过的一个案例中,这曾经导致问题。因此,我建议您在必须添加或减去日期时始终使用NSDATE组件。这是做这件事的正确方法。。请尝试一下,看看它是否有效。

答案就在文档中,这就是问题所在

d 1..2 1日期-当月的第几天 D 1..3每年345天

在您的情况下,您计算的时间间隔具有正确的秒数,但该天是一年中的第一天

如果您按如下方式修改代码以包含月份,您还将得到1(一月)


有什么建议吗?我对这个NSDate的东西不太熟悉看看文件NSDateFormattingGuide@SimonAndersson:检查我的答案。第一个答案含糊不清,第二个是c.cam108的副本。谢谢,如何将其集成到我现在的代码中?那么如何存储秒表的值?startDate是我用来存储秒表启动日期的NSDate。另外,刚刚完全发现问题的来源-请参阅编辑后的答案。非常感谢!我使用了你的答案,将timerValue转换为long,现在它可以工作了!非常感谢!为什么要计算计时器的时间间隔,然后将其添加到1970年1月1日?
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];
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];
[dateFormatter setDateFormat:@"D' Days, 'M' Months, 'H' Hours, 'm' Minutes and 's' Seconds'"];