Swift 擷取目前時間戳 (秒級,毫秒級)

來源:互聯網
上載者:User
Swift 擷取目前時間戳 (秒級,毫秒級)

經常見到有人將 秒級 時間戳記 以 Int 類型直接 *1000 來擷取毫秒,這樣的結果最後的3位元字都是0,擷取到的結果不夠精確。所以擷取毫秒級時間戳記有另外一種方式。 建立一個 Date 的 Extension,代碼如下

    extension Date {    /// 擷取當前 秒級 時間戳記 - 10位    var timeStamp : String {        let timeInterval: TimeInterval = self.timeIntervalSince1970        let timeStamp = Int(timeInterval)        return "\(timeStamp)"    }    /// 擷取當前 毫秒級 時間戳記 - 13位    var milliStamp : String {        let timeInterval: TimeInterval = self.timeIntervalSince1970        let millisecond = CLongLong(round(timeInterval*1000))        return "\(millisecond)"    }}
使用
 let millisecond = Date().milliStamp print("當前毫秒級時間戳記是 millisecond == ",millisecond) let timeStamp = Date().timeStamp print("當前秒級時間戳記是 timeStamp == ",timeStamp)/**     輸出結果    當前毫秒級時間戳記是 millisecond ==  1524801851988    當前秒級時間戳記是 timeStamp ==  1524801851*/
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.