How do I get a Unix Timestamp in Clojure?

22,097

Solution 1

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.

Solution 2

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.))
Share:
22,097
Brad Koch
Author by

Brad Koch

Co-founder: FarmLogs, YC W12 [NYT] [BW] [TC] We're passionate about bringing agriculture online. Come join us! GitHub - LinkedIn

Updated on October 28, 2021

Comments

  • Brad Koch
    Brad Koch over 2 years

    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?