如何将 NSTimeInterval 转换为整数值?
我的 TimeInterval 持有价值83.01837
。我需要将其转换为83
. 我用谷歌搜索但找不到任何帮助。
如何将 NSTimeInterval 转换为整数值?
我的 TimeInterval 持有价值83.01837
。我需要将其转换为83
. 我用谷歌搜索但找不到任何帮助。
直接赋值:
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
根据文档,NSTimeInterval
只是一个double
:
typedef double NSTimeInterval;
您可以将其转换为int
:
seconds = (int) myTimeInterval;
不过要注意溢出!
我怀疑来自 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
斯威夫特 4,斯威夫特 5
我只是投到Int64
:
Int64(Date().timeIntervalSince1970)
我需要将 NSDate 存储在 Swift Number 中。我使用了以下效果很好的演员表。
Double(startDateTime.timeIntervalSince1970)