First, create a new Stimulus controller. Here, we've title it time_zone_setter_controller.js. This controller does one thing: when the controller connects, it updates the value of the field target to the browser's reported time zone.
It reads:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["field"];
connect() {
this.fieldTarget.value = Intl.DateTimeFormat().resolvedOptions().timeZone
}
}In your erb (or whatever) template, set up a hidden field to instantiate the controller and set it to the field target.
<%= form_with model: @user do |f| %>
<%# All your other form fields... %>
<%= f.hidden_field :time_zone, value: "UTC", data: { controller: "time-zone-setter", time_zone_setter_target: "field" } %>
<% end %>Adjust the hidden field's name as needed.