Clojure 基礎

1 minute read

if

(defn if-sample
  ""
  []
  (if true
    (str "this is true")
    (str "tihs is false")))
(if-sample)

getting-clojure リポジトリでさまざまなコード片を記述していきながら基礎を学んでいく

そこで出てきた実装をうまくなにかに生かす

yyyyMMddHHmm の形式の数字列を java.time.LocalDatetime 型にする

  • 数字列からDatetime形式にしてよしなに取り扱いたい要件があった

  • clj-time には clj-time.format の parse, unparse formatter を定義してできたが、java-time に切り替えたら parse がができなさそう

    (ns tmp
      (:require [clj-time.core :as t]
                [clj-time.local :as l]
                [clj-time.format :as f]
                [clj-time.predicates :as pr]
                [clojure.string :as str]
                [java-time :as time])
      (:import [java.time LocalDateTime]
               [java.time.format DateTimeFormatter]))
    
    (def custom-formatter (f/formatter "yyyyMMddHHmm"))
    (f/unparse custom-formatter (t/now))
    (f/parse custom-formatter "202105251003")
    
  • 自作で作ってみたけどこれはどうなのか….

    (defn datetime-parser
      "yyyyMMddHHmm to java.time.localDatetime"
      [s]
      (let [tmp (->>
                 (str/split (str s) #"")
                 (partition 4))
            yyyy (->>
                  (first tmp)
                  (str/join))
            mm (->>
                (second tmp)
                (partition 2)
                (first)
                (str/join))
            dd (->>
                (second tmp)
                (partition 2)
                (second)
                (str/join))
            h (->>
               (last tmp)
               (partition 2)
               (first)
               (str/join))
            m (->>
               (last tmp)
               (partition 2)
               (second)
               (str/join))]
        (time/local-date-time (Integer. yyyy) (Integer. mm)
                              (Integer. dd) (Integer. h)
                              (Integer. m))))
    
    (datetime-parser 202106271918)
    ;; => #object[java.time.LocalDateTime 0xe6abc87 2021-06-27T19:18]