我正在取当前的时间,以UTC为单位,并以纳秒为单位,然后我需要拿出纳秒,然后在当地时间返回一个日期。
我可以得到时间纳秒,然后回到一个日期字符串,但时间是复杂的,当我从一个字符串到日期。
//Date to milliseconds
func currentTimeInMiliseconds() -> Int! {
let currentDate = NSDate()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: dateFormatter.string(from: currentDate as Date))
let nowDouble = date!.timeIntervalSince1970
return Int(nowDouble*1000)
}
//Milliseconds to date
extension Int {
func dateFromMilliseconds(format:String) -> Date {
let date : NSDate! = NSDate(timeIntervalSince1970:Double(self) / 1000.0)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.timeZone = TimeZone.current
let timeStamp = dateFormatter.string(from: date as Date)
let formatter = DateFormatter()
formatter.dateFormat = format
return ( formatter.date( from: timeStamp ) )!
}
}
时间戳是正确的,但返回的日期不是。
发布于 2017-09-19 07:52:53
As @Travis解决方案有效,但在某些情况下
var millisecondsSince1970:Int
将导致应用程序崩溃,
有错误
双值不能转换为Int,因为如果发生Int.max,结果将大于,请使用Int64更新您的答案
这是最新的答案
extension Date {
var millisecondsSince1970:Int64 {
return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
//RESOLVED CRASH HERE
}
init(milliseconds:Int) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
}
}
在32位平台上,Int的大小与Int32相同,而在64位平台上,Int的大小与Int64相同.
通常,我在iPhone 5
中遇到这个问题,它在32位env中运行.新设备现在运行64位env。他们的Int
将是Int64
。
希望这对同样有问题的人有帮助。
https://stackoverflow.com/questions/40134323
复制相似问题