use*_*052 40 time date ios swift
我以UTC的当前时间,并将其置于nanaoseconds,然后我需要花费纳秒并回到当地时间的日期.我能够把时间缩短到纳秒,然后回到日期字符串,但是当我从字符串到日期时,时间会变得复杂.
//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 ) )!
}
}
Run Code Online (Sandbox Code Playgroud)
//时间戳是正确的,但返回的日期不是
Tra*_*ggs 135
我不明白为什么你要用字符串做任何事情......
extension Date {
var millisecondsSince1970:Int64 {
return Int64((self.timeIntervalSince1970 * 1000.0).rounded())
}
init(milliseconds:Int64) {
self = Date(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
}
}
Date().millisecondsSince1970 // 1476889390939
Date(milliseconds: 0) // "Dec 31, 1969, 4:00 PM" (PDT variant of 1970 UTC)
Run Code Online (Sandbox Code Playgroud)
Pra*_*iya 38
正如@Travis解决方案有效,但在某些情况下
var millisecondsSince1970:Int 会引起崩溃应用,
有错误
Double值无法转换为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))
}
}
Run Code Online (Sandbox Code Playgroud)
希望对同样有问题的人有所帮助
在32位平台上,Int与Int32的大小相同,在64位平台上,Int与Int64的大小相同.
一般来说,我遇到了这个问题iPhone 5,它运行在32位环境中.新设备现在运行64位环境.他们的Int意志Int64.
J.S*_*nio 11
@Travis解决方案是正确的,但是在生成Date时它会丢失毫秒.我添加了一行以包含日期中的毫秒数:
如果您不需要此精度,请使用Travis解决方案,因为它会更快.
extension Date {
func toMillis() -> Int64! {
return Int64(self.timeIntervalSince1970 * 1000)
}
init(millis: Int64) {
self = Date(timeIntervalSince1970: TimeInterval(millis / 1000))
self.addTimeInterval(TimeInterval(Double(millis % 1000) / 1000 ))
}
}
Run Code Online (Sandbox Code Playgroud)
//Date to milliseconds
func currentTimeInMiliseconds() -> Int {
let currentDate = Date()
let since1970 = currentDate.timeIntervalSince1970
return Int(since1970 * 1000)
}
//Milliseconds to date
extension Int {
func dateFromMilliseconds() -> Date {
return Date(timeIntervalSince1970: TimeInterval(self)/1000)
}
}
Run Code Online (Sandbox Code Playgroud)
我通过字符串和所有随机删除看似无用的转换!.
| 归档时间: |
|
| 查看次数: |
73232 次 |
| 最近记录: |