NSTimeInterval到NSDate

Bau*_*aub 16 objective-c nsdate nsdateformatter nstimeinterval

我怎样才能转换NSTimeIntervalNSDate?把它想象成一个秒表.我希望初始日期是00:00:00,我有一个NSTimeIntervalX秒.

我需要像这样做,因为NSTimeInterval需要通过使用lround舍入转换为int ,然后转换NSDate为使用NSDateFormatter将其转换为字符串.

Jos*_*ell 34

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);
 }
Run Code Online (Sandbox Code Playgroud)


ole*_*keh 15

这里显示了一个简单的转换和返回:

 NSDate * now = [NSDate date];
 NSTimeInterval  tiNow = [now timeIntervalSinceReferenceDate]; 
 NSDate * newNow = [NSDate dateWithTimeIntervalSinceReferenceDate:tiNow];
Run Code Online (Sandbox Code Playgroud)

Ole K Hornnes


Mat*_*ats 12

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];
Run Code Online (Sandbox Code Playgroud)


Ale*_*hol 6

如果您将初始日期存储在NSDate对象中,则可以在将来的任何时间间隔内获取新日期.只需使用dateByAddingTimeInterval:如下:

NSDate * originalDate = [NSDate date];
NSTimeInterval interval = 1;
NSDate * futureDate = [originalDate dateByAddingTimeInterval:interval];
Run Code Online (Sandbox Code Playgroud)