ios 如何将 NSTimeInterval 转换为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11121459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert NSTimeInterval to int?
提问by Pradeep Reddy Kypa
How do I convert NSTimeInterval into an Integer value?
如何将 NSTimeInterval 转换为整数值?
My TimeInterval holds the value 83.01837
. I need to convert it into 83
. I have googled but couldn't find any help.
我的 TimeInterval 持有价值83.01837
。我需要将其转换为83
. 我用谷歌搜索但找不到任何帮助。
回答by Aaron Hayman
Direct assignment:
直接赋值:
NSTimeInterval interval = 1002343.5432542;
NSInteger time = interval;
//time is now equal to 1002343
NSTimeInterval is a double, so if you assign it directly to a NSInteger (or int, if you wish) it'll work. This will cut off the time to the nearest second.
NSTimeInterval 是一个双精度值,因此如果您将它直接分配给 NSInteger(或 int,如果您愿意),它将起作用。这会将时间截断到最接近的秒。
If you wish to round to the nearest second (rather than have it cut off) you can use round before you make the assignment:
如果您希望四舍五入到最近的秒数(而不是将其截断),则可以在进行分配之前使用 round:
NSTimeInterval interval = 1002343.5432542;
NSInteger time = round(interval);
//time is now equal to 1002344
回答by Emil Vikstr?m
According to the documentation, NSTimeInterval
is just a double
:
根据文档,NSTimeInterval
只是一个double
:
typedef double NSTimeInterval;
You can cast this to an int
:
您可以将其转换为int
:
seconds = (int) myTimeInterval;
Watch out for overflows, though!
不过要注意溢出!
回答by Duncan C
I suspect that NSTimeInterval values from NSDate would overflow an NSInteger. You'd likely want a long long. (64 bit integer.) Those can store honking-big integer values (-2^63 to 2^63 -1)
我怀疑来自 NSDate 的 NSTimeInterval 值会溢出 NSInteger。你可能想要很长很长的。(64 位整数。)那些可以存储喇叭大整数值(-2^63 到 2^63 -1)
long long integerSeconds = round([NSDate timeIntervalSinceReferenceDate]);
EDIT:
编辑:
It looks like an NSInteger CANstore an NSTimeInterval, at least for the next couple of decades. The current date's timeIntervalSinceReferenceDate is about 519,600,000, or about 2^28. On a 32 bit device, and NSInteger can hold a value from -2^31 to 2^31-1. (2^31 is 2,147,483,648
它看起来像一个NSInteger CAN店的NSTimeInterval,至少在未来几十年。当前日期的 timeIntervalSinceReferenceDate 约为 519,600,000,或约为 2^28。在 32 位设备上,NSInteger 可以保存从 -2^31 到 2^31-1 的值。(2^31 是 2,147,483,648
回答by RaffAl
Swift 4, Swift 5
斯威夫特 4、斯威夫特 5
I simply cast to Int64
:
我只是简单地投射到Int64
:
Int64(Date().timeIntervalSince1970)
回答by Justin Domnitz
I had a need to store an NSDate in a Swift Number. I used the following cast which is working great.
我需要将 NSDate 存储在 Swift Number 中。我使用了以下演员,效果很好。
Double(startDateTime.timeIntervalSince1970)