Show the time in user's timezone in Phoenix LiveView

almirsarajcic

almirsarajcic

7 months ago

Here’s an easy way to shift the time/date to the user’s timezone in Phoenix LiveView without introducing new controls in the UI.

# app.js
let timezoneOffset = new Date().getTimezoneOffset()

const liveSocket = new LiveSocket("/live", Socket, {
  longPollFallbackMs: 2500,
  params: {_csrf_token: csrfToken, timezone_offset: timezoneOffset}
})

# index.ex
on mount {__MODULE__, :assign_timezone_offset}

def assign_timezone_offset(_params, _session, socket) do
  timezone =
    if connected?(socket) do
      Phoenix.LiveView.get_connect_params(socket)["timezone_offset"]
    else
      0
    end

  {:cont, assign(socket, :timezone_offset, timezone_offset)}
end

def render(assigns) do
  ~H"""
  Created at: #{NaiveDateTime.add(@post.created_at, timezone_offset, :second)}
  """
end

Of course, you’ll want to extract the on_mount hook so it can be used by multiple liveviews.