如何在 Swift 中获取 18 位当前时间戳? [英] How to get 18-digit current timestamp in Swift?

查看:33
本文介绍了如何在 Swift 中获取 18 位当前时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样获取当前时间戳:

I want to get current timestamp like this:

636110767775716756​

但是,当我这样做时:

NSDate().timeIntervalSince1970

它返回一个这样的值:

1475491615.71278

如何以我想要的格式访问当前时间戳记?我从这里查看日期:

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

推荐答案

您似乎在寻找什么 DateTime.Ticks 在 C# 中,即从 0001-01-01 开始的时间以 100 纳秒为间隔测量.

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

您提供的链接中的代码 Swift:将 NSDate 转换为 c# ticks 可以很容易地翻译成 Swift:

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)
    }
}

示例(Swift 3):

Example (Swift 3):

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

或作为字符串:

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

虽然是在它,从刻度到 Date 的反向转换会

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)
    }
}

示例(Swift 3):

Example (Swift 3):

let date = Date(ticks: 636110903202288256)

这篇关于如何在 Swift 中获取 18 位当前时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆