如何从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