【问题标题】:What are the Clojure time and date libraries? [closed]Clojure 时间和日期库是什么? [关闭]
【发布时间】:2011-02-17 04:09:18
【问题描述】:

我在http://clojure.org/libraries 中找不到处理时间和日期的库。有没有,或者这是我必须弄清楚如何直接用Java做的事情?

【问题讨论】:

    标签: clojure


    【解决方案1】:

    clj-time 是 Java Joda-Time 的包装器。

    如果您使用 Leiningen 或 Maven,您可以通过 Clojars 将其添加到您的项目中。

    GitHub page 上有很多示例,展示了如何进行日期算术和解析/格式化。例如:

    (in-minutes (duration (date-time 1986 10 2) (date-time 1986 10 14)))
    ;; gives 17280
    
    (def custom-formatter (formatter \"yyyyMMdd\"))
    
    (parse custom-formatter "20100311")
    ;; gives #<DateTime 2010-03-11T00:00:00.000Z>
    
    (unparse custom-formatter (date-time 2010 10 3))
    ;; gives "20101003"
    

    【讨论】:

    • 你如何使用这个库获得当前的日期时间?我在 README 中没有看到它。
    • duration 好像改名为interval
    • @Feng 我看了一下 clj-time github issue github.com/clj-time/clj-time/issues/77,看起来库中的持续时间和间隔是不同的概念(持续时间是两次之间的相对距离,与间隔相比有一个绝对的开始和结束)。看起来他们即将重新增加持续时间;如果您(或其他任何人)正在观看它,请在重新添加持续时间时随时编辑答案 - 否则,我想我的答案中的第一个示例可以删除或重述。
    • 我还建议阅读Clojure Cookbook 的第一章(或全部)。它也涵盖了clj-time 的使用。
    • 修改为使用Java 8了吗?
    【解决方案2】:

    这是一个老问题,但 Java 8 中的新 LocalDate 类是完成此任务的不需要库的方法。

    (ns example
      (:import (java.time LocalDate format.DateTimeFormatter)))
    
    (def formatting (DateTimeFormatter/ofPattern
                     "MM/dd/yyyy"))
    
    (LocalDate/parse "08/06/2015" formatting)
    

    【讨论】:

    • 但是 LocalDate/parse 不返回 #inst 文字,而是返回 #object[java.time.LocalDate]...
    • @GillesPhilippart 不管怎样,LocalDates 是不可变的。
    【解决方案3】:

    我以前用过clj-time,它包Joda Time没有任何问题。

    还有dm3/clojure.java-time,它封装了Java 8 Date-Time API。

    从 Clojure 1.8 开始还有一个相关的命名空间:clojure.instant

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多