37

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?

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
  • 2
    Don't use `int`: `(int (/ (.getTimeInMillis (java.util.GregorianCalendar. 2038 1 20)) 1000)) ;=> IllegalArgumentException Value out of range for int: 2150258400`. Try `quot` instead, e.g. `(-> (java.util.Date.) .getTime (quot 1000))`. – A. Webb Jul 02 '13 at 18:26

3 Answers3

67

Pretty much all JVM-based timestamp mechanisms measure time as milliseconds since the epoch - so no, nothing standard** that will give seconds since epoch.

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.

Alex
  • 13,811
  • 1
  • 37
  • 50
20

I'd go with clj-time, the standard Clojure library for dealing with times and dates (wrapping 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:

[clj-time "0.15.2"]

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.))
David Ongaro
  • 3,568
  • 1
  • 24
  • 36
Michał Marczyk
  • 83,634
  • 13
  • 201
  • 212
-3
(defn unix-time-real
  "Taken from
  System/currentTimeMillis."
  []
  (/ (System/currentTimeMillis) 1000))
Édipo Féderle
  • 4,169
  • 5
  • 31
  • 35