38

如何将 NSTimeInterval 转换为整数值?

我的 TimeInterval 持有价值83.01837。我需要将其转换为83. 我用谷歌搜索但找不到任何帮助。

4

6 回答 6

69

直接赋值:

NSTimeInterval interval = 1002343.5432542;
NSInteger time = interval;
//time is now equal to 1002343

NSTimeInterval 是一个双精度,所以如果你直接将它分配给一个 NSInteger (或 int,如果你愿意的话)它会起作用。这会将时间截断到最接近的秒数。

如果您希望四舍五入到最接近的秒数(而不是将其截断),您可以在分配之前使用 round :

NSTimeInterval interval = 1002343.5432542;
NSInteger time = round(interval);
//time is now equal to 1002344
于 2012-06-20T14:12:55.137 回答
8

根据文档NSTimeInterval只是一个double

typedef double NSTimeInterval;

您可以将其转换为int

seconds = (int) myTimeInterval;

不过要注意溢出!

于 2012-06-20T14:13:56.093 回答
7

在 Swift 3.0 中

let timestamp = round(NSDate().timeIntervalSince1970)

在此处输入图像描述

于 2016-09-28T04:43:44.477 回答
6

我怀疑来自 NSDate 的 NSTimeInterval 值会溢出 NSInteger。你可能想要很长很长。(64 位整数。)那些可以存储大整数值(-2^63 到 2^63 -1)

long long integerSeconds = round([NSDate timeIntervalSinceReferenceDate]);

编辑:

它看起来像一个 NSInteger 可以存储一个NSTimeInterval,至少在接下来的几十年里。当前日期的 timeIntervalSinceReferenceDate 大约是 519,600,000,或大约 2^28。在 32 位设备上,NSInteger 可以保存从 -2^31 到 2^31-1 的值。(2^31 是 2,147,483,648

于 2012-06-26T00:55:45.643 回答
2

斯威夫特 4,斯威夫特 5

我只是投到Int64

Int64(Date().timeIntervalSince1970)
于 2019-05-27T14:07:30.203 回答
-2

我需要将 NSDate 存储在 Swift Number 中。我使用了以下效果很好的演员表。

Double(startDateTime.timeIntervalSince1970)
于 2015-08-18T14:35:16.297 回答