Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 views
in Technique[技术] by (71.8m points)

ios - How to get 18-digit current timestamp in Swift?

I want to get current timestamp like this:

636110767775716756?

However, when I do :

NSDate().timeIntervalSince1970

It returns a value like this:

1475491615.71278

How do I access current time stamp ticks in the format I want? I check the dates from here:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You seem be looking for what DateTime.Ticks is in C#, i.e. the time since 0001-01-01 measured in 100-nanosecond intervals.

The code from your provided link Swift: convert NSDate to c# ticks can be translated to Swift easily:

// Swift 2:
extension NSDate {
    var ticks: UInt64 {
        return UInt64((self.timeIntervalSince1970 + 62_135_596_800) * 10_000_000)
    }
}

// Swift 3:
extension Date {
    var ticks: UInt64 {
        return UInt64((self.timeIntervalSince1970 + 62_135_596_800) * 10_000_000)
    }
}

Example (Swift 3):

let ticks = Date().ticks
print(ticks) // 636110903202288256

or as a string:

let sticks = String(Date().ticks)
print(sticks)

And while are are at it, the reverse conversion from ticks to Date would be

// Swift 2:
extension NSDate {
    convenience init(ticks: UInt64) {
        self.init(timeIntervalSince1970: Double(ticks)/10_000_000 - 62_135_596_800)
    }
}

// Swift 3:
extension Date {
    init(ticks: UInt64) {
        self.init(timeIntervalSince1970: Double(ticks)/10_000_000 - 62_135_596_800)
    }
}

Example (Swift 3):

let date = Date(ticks: 636110903202288256)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...