Date to milliseconds and back to date in Swift

后端 未结 9 2099
深忆病人
深忆病人 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条回答
  •  猫巷女王i
    2020-11-29 02:17

    As @Travis Solution works but in some cases

    var millisecondsSince1970:Int WILL CAUSE CRASH APPLICATION ,

    with error

    Double value cannot be converted to Int because the result would be greater than Int.max if it occurs Please update your answer with Int64

    Here is Updated Answer

    extension Date {
     var millisecondsSince1970:Int64 {
            return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) 
            //RESOLVED CRASH HERE
        }
    
        init(milliseconds:Int) {
            self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000))
        }
    }
    

    About Int definitions.

    On 32-bit platforms, Int is the same size as Int32, and on 64-bit platforms, Int is the same size as Int64.

    Generally, I encounter this problem in iPhone 5, which runs in 32-bit env. New devices run 64-bit env now. Their Int will be Int64.

    Hope it is helpful to someone who also has same problem

提交回复
热议问题