Parsing a date string into a date sigil in Elixir

What I was trying to achieve, was to get a person's date of birth from a date_input and calculate the age of that particular person. The problem was that the input was giving back a string like "yyyy-mm-dd" with the date, while I needed a date sigil of the form ~D[yyyy-mm-dd] to use with the `diff/2` function.

```
IO.inspect(date_of_birth) "1978-06-11"
```

So I learned that you can use the from_iso8601!/1 function to parse the date from a string to an Elixir Date sigil.

```
IO.inspect(Date.from_iso8601!(date_of_birth)) ~D[1978-06-11]
```

```
def calculate_age(date_of_birth) do
	date_of_birth
		|> Date.from_iso8601!()
		|> calculate_date_diff()
		|> div(365)
end
```

```
defp calculate_date_diff(date) do
	Date.diff(Date.utc_today(), date)
end
```

Why the private calculate_date_diff() function? Because the Date.diff() takes the oldest date as its second parameter, while using the Elixir pipeline adds the previous functions's result as a first parameter to the next function.

Zeno Popovici
03 Aug 2020
« Back to post