2011-11-01 62 views
15

如何将NSTimeInterval转换为NSDate?把它想象成一个秒表。我想要的最初日期是00:00:00,我有一个NSTimeInterval X秒。NSTimeInterval到NSDate

我需要做的是这样的,因为需要NSTimeInterval通过使用lround围捕被转换成int,然后转换为NSDate使用NSDateFormatter来扔进一个字符串。

回答

32

一个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); 
} 
6

如果您有存储在NSDate对象您最初的约会,你可以得到一个新的日期在未来的任何时间间隔。只需使用dateByAddingTimeInterval:这样的:

NSDate * originalDate = [NSDate date]; 
NSTimeInterval interval = 1; 
NSDate * futureDate = [originalDate dateByAddingTimeInterval:interval]; 
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]; 
+0

完美!正是我需要的! – hfossli

14

从一个简单的转换和背面如下所示:

NSDate * now = [NSDate date]; 
NSTimeInterval tiNow = [now timeIntervalSinceReferenceDate]; 
NSDate * newNow = [NSDate dateWithTimeIntervalSinceReferenceDate:tiNow]; 

奥莱ķ霍思内斯

2

通过apple developers

// 1408709486 - 时间间隔值

NSDate *lastUpdate = [[NSDate alloc] initWithTimeIntervalSince1970:1408709486]; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle]; 

NSLog(@"date time: %@", [dateFormatter stringFromDate:lastUpdate]); 

你会得到: 日期时间:2014年8月22日,下午3:11:26

0

由于乔希回答详细的正确方法,如果你仍然希望间隔是在NSDate格式,你可以使用下面的方法

+ (NSDate *) dateForHour:(int) hour andMinute: (int) minute{ 
    NSDateComponents * components = [NSDateComponents new]; 
    components.hour = hour; 
    components.minute = minute; 
    NSDate * retDate = [[NSCalendar currentCalendar] dateFromComponents:components]; 
return retDate;} 
0

NSTimeIntervalNSDate转换斯威夫特:

let timeInterval = NSDate.timeIntervalSinceReferenceDate() // this is the time interval 
NSDate(timeIntervalSinceReferenceDate: timeInterval)