如何将 NSTimeInterval
转换为 NSDate
?把它想象成一个秒表。我希望初始日期为 00:00:00,并且我的 NSTimeInterval
为 X 秒。
我需要这样做,因为 NSTimeInterval
需要通过使用 lround
舍入转换为 int,然后转换为 NSDate
使用 NSDateFormatter
将其放入字符串中。
最佳答案
NSTimeInterval
,顾名思义,嗯,与NSDate
不代表同一事物。 NSDate
是一个时刻。时间间隔是一段时间。要从一个区间得到一个点,你必须有另一个点。您的问题就像在问“如何将 12 英寸转换为我正在切割的板上的一个点?”嗯,12 英寸,从哪里开始?
您需要选择一个引用日期。这很可能是 NSDate
,表示您启动计数器的时间。然后你可以使用+[NSDate dateWithTimeInterval:sinceDate:]
或 -[NSDate dateByAddingTimeInterval:]
也就是说,我敢肯定您正在倒过来考虑这个问题。您正在尝试显示自某个起点以来耗时,即 间隔,而不是当前时间。每次更新显示时,您应该只使用新的时间间隔。例如(假设您有一个定时器定期触发以进行更新):
- (void) updateElapsedTimeDisplay: (NSTimer *)tim {
// You could also have stored the start time using
// CFAbsoluteTimeGetCurrent()
NSTimeInterval elapsedTime = [startDate timeIntervalSinceNow];
// Divide the interval by 3600 and keep the quotient and remainder
div_t h = div(elapsedTime, 3600);
int hours = h.quot;
// Divide the remainder by 60; the quotient is minutes, the remainder
// is seconds.
div_t m = div(h.rem, 60);
int minutes = m.quot;
int seconds = m.rem;
// If you want to get the individual digits of the units, use div again
// with a divisor of 10.
NSLog(@"%d:%d:%d", hours, minutes, seconds);
}
关于objective-c - NSTimeInterval 到 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7971807/