Get current date/month/year for date_select in template

Hey everyone,

I am struggeling with getting a default value (today for the client) into a date_select. Based on the Phoenix Doc there is a function called Calendar, but it appears to be not available in templates:

        <div class="input-group">
          <%= date_select f, :date, builder: fn b -> %>
            <%= b.(:day, [default: :calendar.day(), class: "form-select"]) %>
            <%= b.(:month, [default: :calendar.month(), class: "form-select"]) %>
            <%= b.(:year, [default: :calendar.year(), class: "form-select"]) %>
          <% end %>
        </div>

gives me:

function :calendar.day/0 is undefined or private

same for

Phoenix.Calendar.day()
Calendar.day()

What is it that I am missing?

Without the builder the following worked:

<%= date_select f, :date, [default: :calendar.local_time(), class: "form-select"] %>

Help is much appreciated!

The following functions will help (note the caveats below):

  • Date.utc_today/0. See h Date.utc_today in iex
  • :calendar.local_time/0 returns {date, time}

Caveats

When you say “today”, which today do you mean? Today, as seen by the server’s time or by the local time where the server is located? By the time as seen by the client? The concept of “what is the date today” has nuances that affect the user experience.

1 Like

Ah sorry - yes it was late yesterday (my yesterday). To clarify: I mean today as seen by the client (i.e. user). Thats why I didnt go with UTC. I will amend my question!

As seen by the client isn’t possible to be derived by the server alone and it needs to be communicated by the client to the server. Therefore no elixir standard function can answer that question for you.

There are various mechanisms to do that:

  1. Use the locale as defined in the accept language header, if that header includes the U extension tz. No browser seems to do that, but its possible for an API-based application.

  2. Reverse lookup the IP address to establish a location and then use a library like tz_world to determine the time zone. Not great since IP addresses are not a reliable indicator of the users preference

  3. Ask the user what timezone they would prefer and send that as a parameter to the request. In my opinion this is to be preferred - users should have the ability to express their preferences. Of course this preference could be stored in a user profile making it easy to determine for authorised users.

3 Likes