-1
我的程序中有一個出生日期變量,格式爲「1954-09-15」。我怎樣才能找到那個使用這個出生日期的人的年齡?如何從clojure出生日期計算年齡?
我的程序中有一個出生日期變量,格式爲「1954-09-15」。我怎樣才能找到那個使用這個出生日期的人的年齡?如何從clojure出生日期計算年齡?
在Clojure中,通常使用clj-time
來處理與時間有關的事情。但是,如果您不想拉扯額外的依賴關係,則可以使用java.time
來解決您的問題。不過,您需要了解Clojure的Java interop,因爲您將通過Clojure使用Java庫。
首先,您必須通過import
導入必需的java依賴關係。
函數age
內部爲輸入字符串(人物的出生日期)具有的模式創建date-formatter
- 在這種情況下,它的格式爲"yyyy-MM-dd"
。
然後,使用創建的date-formatter
解析輸入以創建LocalDate
對象。
之後,創建另一個LocalDate
對象,該對象保存執行時的時間。
最後,您計算兩個創建的LocalDate
對象之間的差異,以年爲單位(`ChronoUnit/YEARS')表示。
(ns age-of-person.core
(:import (java.time LocalDate
format.DateTimeFormatter
Year
temporal.ChronoUnit)))
(defn age [birthdate]
(let [date-formatter (DateTimeFormatter/ofPattern "yyyy-MM-dd")
birthdate (LocalDate/parse birthdate date-formatter)
now (LocalDate/now)
age (.until birthdate now ChronoUnit/YEARS)]
age))
調用看起來age
這樣的方法:
age-of-person.core=> (age "1954-09-15")
62
http://stackoverflow.com/questions/19521146/calculate-age-based-on-date-of-birth – Pramitha
我需要在clojure語言的結果(年) – user123
你看着使用CLJ時間https://github.com/clj-time/clj-time – Scott