¿Cuál es la mejor manera de obtener la fecha y la hora en Clojure?

I need to log some events on a Clojure Client-Server scenario, but it seems to me that Clojure does not provide a date/time function. Can any one confirm this or I am missing something here?! If I am correct then I need to use java interop, right?

preguntado el 08 de enero de 11 a las 19:01

5 Respuestas

If all you need is to get the current time and date for your logger, then this function is OK:

 (defn now [] (new java.util.Date))

Now that you mentioned this, it would be useful to have support for immutable Date objects.

Respondido el 08 de enero de 11 a las 23:01

Great, I think I'd go with (print (.getTime (now))) to preserve reasonable precision in my log files. Thanks. - Ali

(defn now [] (java.util.Date.)) is the canonical version. - Rayne

Java 1.8 agregó el java.time package to the core JDK to clean up many of the frustraciones with the state of date & time in Java. Since java.time is now a widely available part of core Java with a much improved API, I would encourage you to give it the first look when writing new date & time code.

Here's how you can retrieve the current date and time:

(java.time.LocalDateTime/now)

Respondido 23 Oct 18, 20:10

=> (.toString (java.time.LocalDateTime/now)) ;; => "2021-03-23T16:23:14.679916" This is something I felt useful - Laurence Chen

Hay un Clojure-wrapper library for Joda-Time. Or you'll have to use java interop with the standard Java API.

Respondido 28 Abr '16, 03:04

Thanks, but I rather keep my dependencies as low as possible. - Ali

@Ali - a sane date-time library is a dependency you should seriously consider; unfortunately the standard libraries (for a lot of languages) aren't always sufficiently precise. - Kenny Evitt

If you dont need nothing more advanced, just use Java classes.

(.format (java.text.SimpleDateFormat. "MM/dd/yyyy") (new java.util.Date))

Respondido el 26 de diciembre de 15 a las 16:12

Con la clj-time, the Clojure library that wraps the Java Joda Time library, you could use code like the following:

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

(time/now) => #<DateTime 2013-03-31T03:23:47.328Z>

(def time-formatter (time-format/formatters :basic-date-time))  ;; ISO 8601 UTC format
(time-format/unparse custom-formatter (date-time 2010 10 3)) => "20101003T000000.000Z"

One benefit of Joda Time (and hence clj-time) is that new releases support new changes to time zones.

Respondido 28 Abr '16, 02:04

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.