之前通过:
//get date formatted string
//2015/11/28 10:48:12
func toString(dateFormat:String) -> String {
let dateFormatter:NSDateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
let formattedDatetimeStr:String = dateFormatter.stringFromDate(self)
return formattedDatetimeStr
}
let curTime = NSDate()
let curTimeStr = curTime.toString("yyyyMMdd_HHmmss")
可以得到时分秒:
现在想要得到毫秒
swift nsdate milliseconds
Objective-C – 获取毫秒时间戳: – ifziv – 博客频道 – CSDN.NET
好像是:
SSS
即可。
请问怎么样把1308847489毫秒时间转换成2011-07-19这样的时间格式? | iOS开发 – CocoaChina CocoaChina_让移动开发更简单
time – iPhone: How to get current milliseconds? – Stack Overflow
Convert NSDate time in milliseconds as Int32 and Int64 in Swift – Stack Overflow
nsdate – Swift ios date as milliseconds Double or UInt64? – Stack Overflow
let curTime = NSDate()
// let curTimeStr = curTime.toString("yyyyMMdd_HHmmss")
let curTimeStr = curTime.toString("yyyyMMdd_HHmmss.SSS")
可以得到我要的毫秒:
(lldb) po curTime
2016-04-27 03:34:58 +0000
(lldb) po curTimeStr
"20160427_113458.831"
[后记]
后来为了得到毫秒的timestamp,用:
let timestampInt:Int = Int(updateTime.timeIntervalSince1970)
// timestampInt=1461989598
但是只得到了秒的时间戳:1461989598
参考:
time – iPhone: How to get current milliseconds? – Stack Overflow
去试试:
let updateTime:NSDate = eachConversationItem.updateTime
// let timestampInt:Int = Int(updateTime.timeIntervalSince1970)
let timeIntervalInSecFloat:Float = Float(updateTime.timeIntervalSince1970)
let timeIntervalInMsFloat:Float = timeIntervalInSecFloat * 1000
let timestampMsInt:Int = Int(timeIntervalInMsFloat)
gLog.verbose("updateTime=\(updateTime), timeIntervalInSecFloat=\(timeIntervalInSecFloat), timeIntervalInMsFloat=\(timeIntervalInMsFloat), timestampMsInt=\(timestampMsInt)")
//updateTime=2016-04-30 04:13:18 +0000, timeIntervalInSecFloat=1.46199e+09, timeIntervalInMsFloat=1.46199e+12, timestampMsInt=1461989670912
即可。
不过后来遇到:
fatal error: floating point value cannot be converted to Int because it is greater than Int.max
然后去调试发现:
(lldb) po Int.max
2147483647
果然是,毫秒的timestamp,比如:
1461989670912
是比Int.max大多了。。。
所以要去改为int64:
直接改为Int64,会导致字典型变量无法正常的当作AnyObject被传入其他参数,
最后改为:
let timestampMsInt:NSNumber = NSNumber(longLong: Int64(timeIntervalInMsFloat))
转载请注明:在路上 » [已解决]swift中格式化NSDate得到毫秒数