简体   繁体   English

如何在Clojure中获取Unix时间戳?

[英]How do I get a Unix Timestamp in Clojure?

I want to know what the current timestamp is. 我想知道当前的时间戳是什么。 The best I can do thus far is define my own function that does this: 到目前为止,我能做的最好的事情就是定义我自己的函数:

(int (/ (.getTime (java.util.Date.)) 1000))

Is there a standard function for fetching the Unix timestamp with clojure? 是否有一个标准函数用于获取clojure的Unix时间戳?

Pretty much all JVM-based timestamp mechanisms measure time as milliseconds since the epoch - so no, nothing standard** that will give seconds since epoch. 几乎所有基于JVM的时间戳机制都将时间测量为自纪元以来的毫秒数 - 所以没有,没有任何标准**会给出自纪元以来的秒数。

Your function can be slightly simplified as: 您的功能可以略微简化为:

(quot (System/currentTimeMillis) 1000)

** Joda might have something like this, but pulling in a third-party library for this seems like overkill. ** Joda可能会有这样的东西,但是为了这个而拉入第三方库似乎有点矫枉过正。

I'd go with clj-time , the standard Clojure library for dealing with times and dates (wrapping Joda-Time ). 我会选择clj-time ,标准的Clojure库来处理时间和日期(包装Joda-Time )。 Yes, it is an extra dependency for a simple need and may be overkill if you really only want the current timestamp; 是的,它是一个额外的依赖,只是一个简单的需要,如果你真的只想要当前的时间戳,可能会有点过分; even then it's just a nice convenience at virtually no cost. 即便如此,这只是一个很好的便利,几乎没有成本。 And if you do eventually come to need additional time-related functionality, then it'll be there with a great implementation of all the basics. 如果你最终需要额外的与时间相关的功能,那么它将在所有基础知识中实现。

As for the code, here's the Leiningen dependency specifier for the current release: 至于代码,这里是当前版本的Leiningen依赖项说明符:

[clj-time "0.5.1"]

And here's a snippet for getting the current timestamp: 这里有一个获取当前时间戳的片段:

(require '[clj-time.core :as time]
         '[clj-time.coerce :as tc])

;; milliseconds since Unix epoch
(tc/to-long (time/now))

;; also works, as it would with other JVM date and time classes
(tc/to-long (java.util.Date.))
(defn unix-time-real
  "Taken from
  System/currentTimeMillis."
  []
  (/ (System/currentTimeMillis) 1000))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM