Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 865
Brad Koch Avatar asked Jul 02 '13 17:07

Brad Koch


2 Answers

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.

like image 95
Alex Avatar answered Sep 23 '22 22:09

Alex


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.)) 
like image 25
Michał Marczyk Avatar answered Sep 20 '22 22:09

Michał Marczyk