objective-c - NSTimeInterval 到 NSDate

标签 objective-c nsdate nsdateformatter nstimeinterval

如何将 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/

相关文章:

objective-c - Quartz Composer 中的 RGB 曲线

objective-c - Objective C 中的 NSData 到 NSString

ios - NSDateComponents 不返回日期

ios - 如何用 "Today at xx:xx pm", "Yesterday at xx:xx am"之类的人类语言显示日期?

ios - 使用 NSDateFormatter 显示日期

objective-c - 重用从文件读取的代码仅在第二类中导致 EXC_BAD_ACCESS

objective-c - 在 ubuntu 上不用 gnustep 编译 objective-c 程序

iphone - 形成谓词以在日期之间进行过滤

swift - 如何在 Swift 3 中将 "2017-01-09T11:00:00.000Z"转换为日期?

ios - NSDateFormatter "Month"3 个字母而不是完整的单词