如何将 a 转换NSTimeInterval
为NSDate
?把它想象成一个秒表。我希望初始日期为 00:00:00,并且我有NSTimeInterval
X 秒。
我需要这样做,因为NSTimeInterval
需要通过使用lround
四舍五入将其转换为int,然后转换为aNSDate
以使用NSDateFormatter
将其放入字符串中。
如何将 a 转换NSTimeInterval
为NSDate
?把它想象成一个秒表。我希望初始日期为 00:00:00,并且我有NSTimeInterval
X 秒。
我需要这样做,因为NSTimeInterval
需要通过使用lround
四舍五入将其转换为int,然后转换为aNSDate
以使用NSDateFormatter
将其放入字符串中。
就像它的NSTimeInterval
名字,嗯,暗示的那样,不代表与 a 相同的东西NSDate
。AnNSDate
是一个时刻。时间间隔是一段时间。要从一个区间得到一个点,你必须有另一个点。您的问题就像在问“如何将 12 英寸转换为我正在切割的板上的一个点?” 那么,12英寸,从哪里开始?
您需要选择一个参考日期。这很可能NSDate
代表您开始计数器的时间。然后你可以使用+[NSDate dateWithTimeInterval:sinceDate:]
或-[NSDate dateByAddingTimeInterval:]
也就是说,我很确定你是在倒退考虑这个问题。您试图显示自某个起点以来经过的时间,即interval,而不是当前时间。每次更新显示时,您应该只使用新的间隔。例如(假设您有一个定期触发的计时器来进行更新):
- (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);
}
此处显示了一个简单的往返转换:
NSDate * now = [NSDate date];
NSTimeInterval tiNow = [now timeIntervalSinceReferenceDate];
NSDate * newNow = [NSDate dateWithTimeIntervalSinceReferenceDate:tiNow];
奥莱·霍恩斯
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];
如果您将初始日期存储在NSDate
对象中,则可以在未来的任何时间间隔内获取新日期。像这样简单地使用dateByAddingTimeInterval:
:
NSDate * originalDate = [NSDate date];
NSTimeInterval interval = 1;
NSDate * futureDate = [originalDate dateByAddingTimeInterval:interval];
通过苹果开发者:
//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
NSTimeInterval
NSDate
在 Swift中转换:
let timeInterval = NSDate.timeIntervalSinceReferenceDate() // this is the time interval
NSDate(timeIntervalSinceReferenceDate: timeInterval)
正如 Josh 的回答详细说明了正确的方法,如果您仍然希望间隔采用 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;}