Date to milliseconds and back to date in Swift

后端 未结 9 2097
深忆病人
深忆病人 2020-11-29 01:53

I am taking the current time, in UTC, and putting it in nanaoseconds and then I need to take the nanoseconds and go back to a date in local time. I am able to do get the tim

9条回答
  •  星月不相逢
    2020-11-29 02:10

    @Travis solution is right, but it loses milliseconds when a Date is generated. I have added a line to include the milliseconds into the date:

    If you don't need this precision, use the Travis solution because it will be faster.

    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 ))
        }
    
    }
    

提交回复
热议问题