-1

I have a date of birth variable in my program in the format "1954-09-15". How can I find the age of that person using this date of birth?

user123
  • 35
  • 1
  • 5
  • http://stackoverflow.com/questions/19521146/calculate-age-based-on-date-of-birth – Pramitha Feb 14 '17 at 05:07
  • i need the result in clojure language (in years) – user123 Feb 14 '17 at 05:09
  • 2
    have you looked in to using clj-time https://github.com/clj-time/clj-time – Scott Feb 14 '17 at 15:24
  • To be fair to the OP, this question is [massively upvoted](http://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c?rq=1) for other languages. That being said, @MelvinSGeorge, the answer is easily found in existing online documentation and blogs. – tar Feb 14 '17 at 20:10
  • http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java – cfrick Feb 15 '17 at 10:26

1 Answers1

1

In Clojure it is common to use clj-time for processing having to do with time. But if you don't want to pull an additional dependency you can use java.time for your problem. You need to understand Java interop from Clojure, though, as you would be using a Java library through Clojure.

First you have to import the necessary java dependencies through import.

Inside the function age you create a date-formatter for the pattern that your input string (the birthdate of the person) has - in this case it's "yyyy-MM-dd".

Then you parse the input using the created date-formatter to create a LocalDate object.

After that you create another LocalDate object that holds the time at the moment of execution.

In the end you calculate the difference between the two created LocalDate objects, expressed in years (`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))

Calling the method age would look like this:

age-of-person.core=> (age "1954-09-15")
62
MicSokoli
  • 841
  • 6
  • 11