2017-02-23 54 views
0

试图找出什么是获得当前时间和MySQL记录的日期时间之间的差异的最佳方式。Clojure:现在和一条记录之间的时间差SQL日期时间

这里是我的代码

(ns clojure.example.hello 
    (:require [clj-time.coerce :as coerce] 
      [clj-time.local :as l])) 

(let [timenow (l/local-now) ;; #object[org.joda.time.DateTime 0x333e8ce5 2017-02-23T21:44:11.022+11:00] 
     last-update (gettimelogged :timestamp) 
     ;; returns SQL datetime which is 2017-02-23 19:20:15, 
     ;; but gets converted into #inst "2017-02-23T08:20:15.000000000-00:00"] 

(println (timenow - lastupdate))) 

什么是运行timenow和最后更新的比较的最佳方式的一个片段?

此外,如果需要更新时间戳,最好的方法是什么?假如我想懒惰地将它加载到clojure,有时像{:NAME“Jim”:AGE“24”:CHECKDATE“NOW()”}

+0

区别?女士? NS? – ClojureMostly

+0

可能在几秒钟内不同将是最好的 – Stixxxx

回答

0

假设您有一个即时值(以#inst ...),可以使用clojure中的inst-ms函数将其转换为毫秒,然后与毫秒中的当前时间进行比较。

(let [db-ms (inst-ms #inst"2017-02-23T08:20:15.000000000-00:00") 
     now-ms (System/currentTimeMillis)] 
    (println "Difference is" (- now-ms db-ms) "ms")) 

如果你不使用的Clojure 1.9,您只需拨打.getTimeinst

(.getTime #inst"2017") 

要使用MySQL插入当前时间,你有几个选项,包括使用内置的NOW()函数,您可以使用它来访问honeysql。

然而,对于一个纯粹的基于JBDC的方法,使用CLJ-time.coerce的帮助,因为你已经使用:以秒

(defn get-sql-now [] 
    (-> (System/currentTimeMillis) 
     coerce/from-long 
     coerce/to-sql-time)) 

(j/insert! mysql-db "joshtable" {:name "Jim" 
           :age 24 
           :checkdate (get-sql-now)}) 
+0

使用inst-ms的问题'(let [zyx(inst-ms #inst“2017-02-23T08:20:15.000000000-00:00”)](println zyx))''。我得到了'CompilerException java.lang.RuntimeException:无法解析symbol:inst-ms在这个上下文中编译'。我正在使用Clojure 1.8.0,我应该使用不同的版本吗? – Stixxxx

+0

@Stixxxx我刚刚更新了答案。改为调用'(.getTime #inst“2017”)''。 – Josh

+0

谢谢你的工作很棒! – Stixxxx