Calculating age of the user

Hello,
I want to calculate age of the user in a template, I tried to use:


<%= Date.diff(Date.utc_today(), user.birth) %>

But in that case user.birth returns nill, but when I put in a bracket like that

<%= Date.diff(Date.utc_today(), {user.birth}) %>

It gives me an error but the date is visible (in a bracket).

How can I solve it?

Please add the error you’re seeing as well.

no function clause matching in Date.diff/2
# FunctionClauseError at GET /users

Exception:

    ** (FunctionClauseError) no function clause matching in Date.diff/2
        (elixir 1.12.2) lib/calendar/date.ex:685: Date.diff(~D[2023-02-03], nil)
        (venue 0.1.0) lib/venue_web/templates/users/index.html.heex:10: anonymous fn/3 in VenueWeb.UsersView."index.html"/1
        (elixir 1.12.2) lib/enum.ex:2385: Enum."-reduce/3-lists^foldl/2-0-"/3
        (venue 0.1.0) lib/venue_web/templates/users/index.html.heex:2: anonymous fn/2 in VenueWeb.UsersView."index.html"/1
        (phoenix_live_view 0.17.12) lib/phoenix_live_view/engine.ex:124: Phoenix.HTML.Safe.Phoenix.LiveView.Rendered.to_iodata/1
        (phoenix_live_view 0.17.12) lib/phoenix_live_view/engine.ex:140: Phoenix.HTML.Safe.Phoenix.LiveView.Rendered.to_iodata/3
        (phoenix 1.6.15) lib/phoenix/controller.ex:772: Phoenix.Controller.render_and_send/4
        (venue 0.1.0) lib/venue_web/controllers/users_controller.ex:1: VenueWeb.UsersController.action/2
        (venue 0.1.0) lib/venue_web/controllers/users_controller.ex:1: VenueWeb.UsersController.phoenix_controller_pipeline/2
        (phoenix 1.6.15) lib/phoenix/router.ex:354: Phoenix.Router.__call__/2
        (venue 0.1.0) lib/venue_web/endpoint.ex:1: VenueWeb.Endpoint.plug_builder_call/2
        (venue 0.1.0) lib/plug/debugger.ex:136: VenueWeb.Endpoint."call (overridable 3)"/2
        (venue 0.1.0) lib/venue_web/endpoint.ex:1: VenueWeb.Endpoint.call/2
        (phoenix 1.6.15) lib/phoenix/endpoint/cowboy2_handler.ex:54: Phoenix.Endpoint.Cowboy2Handler.init/4
        (cowboy 2.9.0) /home/zervis/Dokumenty/GitHub/venue/deps/cowboy/src/cowboy_handler.erl:37: :cowboy_handler.execute/2
        (cowboy 2.9.0) /home/zervis/Dokumenty/GitHub/venue/deps/cowboy/src/cowboy_stream_h.erl:306: :cowboy_stream_h.execute/3
        (cowboy 2.9.0) /home/zervis/Dokumenty/GitHub/venue/deps/cowboy/src/cowboy_stream_h.erl:295: :cowboy_stream_h.request_process/3
        (stdlib 3.17) proc_lib.erl:226: :proc_lib.init_p_do_apply/3
    

Code:

`lib/calendar/date.ex`

    No code available.

  Called with 2 arguments

  * `~D[2023-02-03]`
  * `nil`
  
  Attempted function clauses (showing 2 out of 2)

     def diff(%{calendar: Calendar.ISO} = date1, %{calendar: Calendar.ISO} = date2)
     def diff(%{calendar: calendar1} = date1, %{calendar: calendar2} = date2)
    

`lib/venue_web/templates/users/index.html.heex`

    5   <%= user.email %>
    6   <% end %>
    7   
    8   <%= img_tag Venue.Avatar.url({user.avatar, user}, :thumb, signed: true) %>
    9   
    10>  <%= Date.diff(Date.utc_today(), user.birth) %>
    11   <%= user.birth %>
    12   <%= user.desc %>
    13   
    14   <%= trunc(Geocalc.distance_between(user.geom.coordinates, @current_user.geom.coordinates) / 1000) %> km <br>
    15   
    
`lib/enum.ex`

    No code available.

`lib/venue_web/templates/users/index.html.heex`

    1   <%= if @current_user do %>
    2>  <%= for user <- @users do %>
    3   
    4   <%= link to: Routes.users_path(@conn, :show, user.id) do %>
    5   <%= user.email %>
    6   <% end %>
    7   
    
`lib/phoenix_live_view/engine.ex`

    119             root: nil | true | false
    120           }
    121   
    122     defimpl Phoenix.HTML.Safe do
    123       def to_iodata(%Phoenix.LiveView.Rendered{static: static, dynamic: dynamic}) do
    124>        to_iodata(static, dynamic.(false), [])
    125       end
    126   
    127       def to_iodata(%_{} = struct) do
    128         Phoenix.HTML.Safe.to_iodata(struct)
    129       end
    
`lib/phoenix_live_view/engine.ex`

    135       def to_iodata(other) do
    136         other
    137       end
    138   
    139       defp to_iodata([static_head | static_tail], [dynamic_head | dynamic_tail], acc) do
    140>        to_iodata(static_tail, dynamic_tail, [to_iodata(dynamic_head), static_head | acc])
    141       end
    142   
    143       defp to_iodata([static_head], [], acc) do
    144         Enum.reverse([static_head | acc])
    145       end
    
`lib/phoenix/controller.ex`

    767         Map.get(conn.private, :phoenix_view) ||
    768           raise "a view module was not specified, set one with put_view/2"
    769   
    770       layout_format? = format in layout_formats(conn)
    771       conn = prepare_assigns(conn, assigns, template, format, layout_format?)
    772>      data = render_with_layouts(conn, view, template, format, layout_format?)
    773   
    774       conn
    775       |> ensure_resp_content_type(MIME.type(format))
    776       |> send_resp(conn.status || 200, data)
    777     end
    
`lib/venue_web/controllers/users_controller.ex`

    1>  defmodule VenueWeb.UsersController do
    2     use VenueWeb, :controller
    3   
    4     alias Venue.Users
    5     alias VenueWeb.UserAuth
    6     alias Venue.Events
    
`lib/venue_web/controllers/users_controller.ex`

    1>  defmodule VenueWeb.UsersController do
    2     use VenueWeb, :controller
    3   
    4     alias Venue.Users
    5     alias VenueWeb.UserAuth
    6     alias Venue.Events
    
`lib/phoenix/router.ex`

    349           metadata = %{metadata | conn: halted_conn}
    350           :telemetry.execute([:phoenix, :router_dispatch, :stop], measurements, metadata)
    351           halted_conn
    352         %Plug.Conn{} = piped_conn ->
    353           try do
    354>            plug.call(piped_conn, plug.init(opts))
    355           else
    356             conn ->
    357               measurements = %{duration: System.monotonic_time() - start}
    358               metadata = %{metadata | conn: conn}
    359               :telemetry.execute([:phoenix, :router_dispatch, :stop], measurements, metadata)
    
`lib/venue_web/endpoint.ex`

    1>  defmodule VenueWeb.Endpoint do
    2     use Phoenix.Endpoint, otp_app: :venue
    3   
    4     # The session will be stored in the cookie and signed,
    5     # this means its contents can be read but not tampered with.
    6     # Set :encryption_salt if you would also like to encrypt it.
    
`lib/plug/debugger.ex`

    No code available.

`lib/venue_web/endpoint.ex`

    1>  defmodule VenueWeb.Endpoint do
    2     use Phoenix.Endpoint, otp_app: :venue
    3   
    4     # The session will be stored in the cookie and signed,
    5     # this means its contents can be read but not tampered with.
    6     # Set :encryption_salt if you would also like to encrypt it.
    
`lib/phoenix/endpoint/cowboy2_handler.ex`

    49             end
    50   
    51           {:plug, conn, handler, opts} ->
    52             %{adapter: {@connection, req}} =
    53               conn
    54>              |> handler.call(opts)
    55               |> maybe_send(handler)
    56   
    57             {:ok, req, {handler, opts}}
    58         end
    59       catch
    
`/home/zervis/Dokumenty/GitHub/venue/deps/cowboy/src/cowboy_handler.erl`

    32   -optional_callbacks([terminate/3]).
    33   
    34   -spec execute(Req, Env) -> {ok, Req, Env}
    35   	when Req::cowboy_req:req(), Env::cowboy_middleware:env().
    36   execute(Req, Env=#{handler := Handler, handler_opts := HandlerOpts}) ->
    37>  	try Handler:init(Req, HandlerOpts) of
    38   		{ok, Req2, State} ->
    39   			Result = terminate(normal, Req2, State, Handler),
    40   			{ok, Req2, Env#{result => Result}};
    41   		{Mod, Req2, State} ->
    42   			Mod:upgrade(Req2, Env, Handler, State);
    
`/home/zervis/Dokumenty/GitHub/venue/deps/cowboy/src/cowboy_stream_h.erl`

    301   	end.
    302   
    303   execute(_, _, []) ->
    304   	ok;
    305   execute(Req, Env, [Middleware|Tail]) ->
    306>  	case Middleware:execute(Req, Env) of
    307   		{ok, Req2, Env2} ->
    308   			execute(Req2, Env2, Tail);
    309   		{suspend, Module, Function, Args} ->
    310   			proc_lib:hibernate(?MODULE, resume, [Env, Tail, Module, Function, Args]);
    311   		{stop, _Req2} ->
    
`/home/zervis/Dokumenty/GitHub/venue/deps/cowboy/src/cowboy_stream_h.erl`

    290   %% to simplify the debugging of errors. The proc_lib library
    291   %% already adds the stacktrace to other types of exceptions.
    292   -spec request_process(cowboy_req:req(), cowboy_middleware:env(), [module()]) -> ok.
    293   request_process(Req, Env, Middlewares) ->
    294   	try
    295>  		execute(Req, Env, Middlewares)
    296   	catch
    297   		exit:Reason={shutdown, _}:Stacktrace ->
    298   			erlang:raise(exit, Reason, Stacktrace);
    299   		exit:Reason:Stacktrace when Reason =/= normal, Reason =/= shutdown ->
    300   			erlang:raise(exit, {Reason, Stacktrace}, Stacktrace)
    
`proc_lib.erl`

    No code available.


## Connection details

### Params

    %{}

### Request info

  * URI: http://localhost:4000/users
  * Query string: 

### Headers
  
  * accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
  * accept-encoding: gzip, deflate, br
  * accept-language: pl,en-US;q=0.7,en;q=0.3
  * connection: keep-alive
  * cookie: _venue_key=SFMyNTY.g3QAAAADbQAAAAtfY3NyZl90b2tlbm0AAAAYTVpENTdrX0NyMWNiRTZvUWhwLTE2NlZObQAAAA5saXZlX3NvY2tldF9pZG0AAAA7dXNlcnNfc2Vzc2lvbnM6VWJPVW5pMXJMZ3JabVJqbUNwSnNFeUk5MGtaOGFLTDRrTmpEU1g5cDNhND1tAAAACnVzZXJfdG9rZW5tAAAAIFGzlJ4tay4K2ZkY5gqSbBMiPdJGfGii-JDYw0l_ad2u.Ywj13HQxgpyztHM1QCUMuKAYCRpf3iZCf-RAGsz0X2w
  * host: localhost:4000
  * referer: http://localhost:4000/
  * sec-fetch-dest: document
  * sec-fetch-mode: navigate
  * sec-fetch-site: same-origin
  * upgrade-insecure-requests: 1
  * user-agent: Mozilla/5.0 (X11; Linux x86_64; rv:103.0) Gecko/20100101 Firefox/103.0

### Session

    %{"_csrf_token" => "MZD57k_Cr1cbE6oQhp-166VN", "live_socket_id" => "users_sessions:UbOUni1rLgrZmRjmCpJsEyI90kZ8aKL4kNjDSX9p3a4=", "user_token" => <<81, 179, 148, 158, 45, 107, 46, 10, 217, 153, 24, 230, 10, 146, 108, 19, 34, 61, 210, 70, 124, 104, 162, 248, 144, 216, 195, 73, 127, 105, 221, 174>>}
lib/calendar/date.ex
'''
'''
Date.diff/2
Called with 2 arguments

    ~D[2023-02-03]
    nil

Attempted function clauses (showing 2 out of 2)

def diff(%{calendar: Calendar.ISO} = date1, %{calendar: Calendar.ISO} = date2) def diff(%{calendar: calendar1} = date1, %{calendar: calendar2} = date2)
'''

Date.diff/2 requires both parameters to be %DateTime{} structs. user.birth seems to be nil.

Ha, I know why. Some of users didn’t have date in their profile.

Thanks!