最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift把NSDate时间变成时间戳

iOS crifan 2255浏览 0评论
//: Playground – noun: a place where people can play
import UIKit
extension NSDate {
    //convert time to Int64 timestamp:
    //-> in millisecond -> 13 digits: 1466576142336
    //-> in second      -> 10 digits: 1466576128
    func toTimestamp(toMilliSec:Bool = true) -> Int64 {
        var curTimestamp:Int64 = 0
        print(“self=\(self)”)
        print(“self.timeIntervalSince1970=\(self.timeIntervalSince1970)”)
        //1466576025.00243
        var curTimestampFloat = Float(self.timeIntervalSince1970)
        print(“curTimestampFloat=\(curTimestampFloat)”)
        if toMilliSec {
            curTimestampFloat = curTimestampFloat * 1000
            print(“timestampFloat=\(curTimestampFloat)”)
        }
        curTimestamp = Int64(curTimestampFloat)
        print(“curTimestamp=\(curTimestamp)”)
        //1466576025002
        //1466576025
        return curTimestamp
    }
    func toTimestampInSec() -> Int64 {
        return self.toTimestamp(false)
    }
}
let curTime = NSDate()
print(“curTime=\(curTime)”)
//let timeIntervalInSecFloat:Float = Float(curTime.timeIntervalSince1970)
//print(“timeIntervalInSecFloat=\(timeIntervalInSecFloat)”)
//
//let timeIntervalInMsFloat:Float = timeIntervalInSecFloat * 1000
//print(“timeIntervalInMsFloat=\(timeIntervalInMsFloat)”)
//curTime.toTimestamp(false)
curTime.toTimestamp()

即可:

curTime=2016-06-22 06:16:06 +0000
self=2016-06-22 06:16:06 +0000
self.timeIntervalSince1970=1466576166.77657
curTimestampFloat=1.46658e+09
timestampFloat=1.46658e+12
curTimestamp=1466576142336

curTime.toTimestamp(false)

-》

curTime=2016-06-22 06:18:06 +0000
self=2016-06-22 06:18:06 +0000
self.timeIntervalSince1970=1466576286.4994
curTimestampFloat=1.46658e+09
curTimestamp=1466576256

更新更全代码详见:

https://github.com/crifan/crifanLib/blob/master/swift/CrifanNSDate.swift

转载请注明:在路上 » [已解决]swift把NSDate时间变成时间戳

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
90 queries in 0.215 seconds, using 22.09MB memory