NSTimeInterval到NSDate [英] NSTimeInterval to NSDate

查看:110
本文介绍了NSTimeInterval到NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将NSTimeInterval转换为NSDate?可以把它想像成秒表.我希望初始日期为00:00:00,并且我有X秒的NSTimeInterval.

How can I convert a NSTimeInterval to NSDate? Think of it like a stopwatch. I want the initial date to be 00:00:00, and I have a NSTimeInterval of X seconds.

我需要这样做,因为NSTimeInterval需要通过使用lround进行四舍五入而转换为int,然后转换为NSDate以便使用NSDateFormatter将其扔到字符串中.

I need to do it like this because the NSTimeInterval needs to be converted to an int by using lround to round up, then converted to a NSDate to use the NSDateFormatter to throw it into a string.

推荐答案

NSTimeInterval顾名思义,与NSDate并不相同. NSDate是时间 .时间间隔是一段时间.要从间隔中得到一个点,您必须有另一个点.您的问题就像问如何将12英寸转换为我要切割的板上的一个点?"好吧,这是12英寸,从从哪里开始?

An NSTimeInterval, as its name, um, implies, doesn't represent the same thing as an NSDate. An NSDate is a moment in time. A time interval is a stretch of time. To get a point from an interval, you have to have another point. Your question is like asking "How do I convert 12 inches to a spot on this board I'm cutting?" Well, 12 inches, starting from where?

您需要选择一个参考日期.这很可能是NSDate,代表您启动计数器的时间.然后,您可以使用

You need to pick a reference date. This will most likely be the NSDate representing the time that you started your counter. Then you can use +[NSDate dateWithTimeInterval:sinceDate:] or -[NSDate dateByAddingTimeInterval:]

也就是说,我很确定您正在考虑这个问题.您正在尝试显示从某个起点(即 interval )开始经过的时间,而不是当前时间.每次更新显示时,您都应该使用新的时间间隔.例如(假设您有一个计时器定期触发以进行更新):

That said, I'm pretty sure you're thinking about this backwards. You're trying to display time elapsed since some starting point, i.e., the interval, not the current time. Every time you update the display, you should just be using the new interval. For example (assuming you have a timer firing periodically to do the update):

- (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);
 }

这篇关于NSTimeInterval到NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆