简体   繁体   English

在Clojure中获取日期和时间的最佳方式是什么?

[英]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. 我需要在Clojure Client-Server方案中记录一些事件,但在我看来,Clojure不提供日期/时间功能。 Can any one confirm this or I am missing something here?! 任何人都可以证实这一点,或者我在这里遗漏了什么?! If I am correct then I need to use java interop, right? 如果我是正确的那么我需要使用java互操作,对吧?

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. 既然你提到了这一点,那么支持不可变的Date对象会很有用。

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. Java 1.8将java.time包添加到核心JDK中,以清除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. 由于java.time现在是核心Java的一个广泛可用的部分,具有大大改进的API,我建议您在编写新的日期和时间代码时首先考虑它。

Here's how you can retrieve the current date and time: 以下是检索当前日期和时间的方法:

(java.time.LocalDateTime/now)

There is a Clojure-wrapper library for Joda-Time . Joda-Time有一个Clojure包装库 Or you'll have to use java interop with the standard Java API. 或者您必须使用Java interop与标准Java API。

With clj-time , the Clojure library that wraps the Java Joda Time library, you could use code like the following: 使用clj-time ,包装Java Joda Time库的Clojure库,您可以使用如下代码:

(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. Joda Time(以及clj-time)的一个好处是新版本支持对时区的新更改。

如果你不需要更高级的东西,只需使用Java类。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM