Date to milliseconds and back to date in Swift

后端 未结 9 2073
深忆病人
深忆病人 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:34

    Heres a simple solution in Swift 5/iOS 13.

    extension Date {
        
        func toMilliseconds() -> Int64 {
            Int64(self.timeIntervalSince1970 * 1000)
        }
    
        init(milliseconds:Int) {
            self = Date().advanced(by: TimeInterval(integerLiteral: Int64(milliseconds / 1000)))
        }
    }
    

    This however assumes you have calculated the difference between UTF time and local time and adjusted and accounted for in the milliseconds. For that look to calendar

    var cal = Calendar.current
    cal.timeZone = TimeZone(abbreviation: "UTC")!
    let difference = cal.compare(dateGiven, to: date, toGranularity: .nanosecond)
    

提交回复
热议问题