Ali
Ali

Reputation: 19672

What is the best way to get date and time in 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?

Upvotes: 51

Views: 46715

Answers (6)

practicalli-johnny
practicalli-johnny

Reputation: 1916

java.time is available in Java 8 onward and is a relatively straight forward approach to creating a time stamp for logs

java.time namespace is included in Clojure by default, so available without the need for a `require expression.

(java.time.LocalDate/now)

Evaluating this expression returns a Java Time object which should work with most log frameworks

#object[java.time.LocalDate 0x5814b4fb "2023-07-13"]

For example, in mulog the following event log includes a date-time stamp

(ns practicalli.gameboard.system
  "Service component lifecycle management"
  (:gen-class)
  (:require
   [com.brunobonacci.mulog :as mulog]))

(mulog/log 
  ::log-publish-component
  :local-time (java.time.LocalDateTime/now))

NOTE: change the namespace to match the file name or add a suitable require to your namespace and copy the mulog/log expression

Upvotes: 0

Brad Koch
Brad Koch

Reputation: 20267

Java 1.8 added the java.time package to the core JDK to clean up many of the frustrations 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)

Upvotes: 41

robert_x44
robert_x44

Reputation: 9314

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

Upvotes: 19

Kenny Evitt
Kenny Evitt

Reputation: 9791

With 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.

Upvotes: 13

&#201;dipo F&#233;derle
&#201;dipo F&#233;derle

Reputation: 4257

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

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

Upvotes: 13

Goran Jovic
Goran Jovic

Reputation: 9508

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.

Upvotes: 57

Related Questions