如何将NSTimeInterval转换为NSDate?把它想象成一个秒表。我希望初始日期是00:00:00,并且我的NSTimeInterval是X秒。
我需要这样做,因为需要通过使用lround向上舍入将NSTimeInterval转换为int,然后转换为NSDate以使用NSDateFormatter将其抛出为字符串。
发布于 2011-11-02 03:54:59
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);
}发布于 2013-07-24 20:08:52
这里显示了一个简单的来回转换:
NSDate * now = [NSDate date];
NSTimeInterval tiNow = [now timeIntervalSinceReferenceDate];
NSDate * newNow = [NSDate dateWithTimeIntervalSinceReferenceDate:tiNow];Ole K Hornnes
发布于 2011-11-02 04:11:57
如果您希望显示时间间隔,我建议您不要使用NSDateFormatter。当您希望显示本地或特定时区的时间时,NSDateFormatter非常有用。但在这种情况下,如果时间调整了时区(例如,一年中的一天有23个小时),这将是一个错误。
NSTimeInterval time = ...;
NSString *string = [NSString stringWithFormat:@"%02li:%02li:%02li",
lround(floor(time / 3600.)) % 100,
lround(floor(time / 60.)) % 60,
lround(floor(time)) % 60];https://stackoverflow.com/questions/7971807
复制相似问题