I am re-writing this post for clarify and to show what I have so far and where exactly I am stuck.
So as you may know, the local_time gem only works when rendering the date and time attributes from the record itself, such as:
local_time(@events.start_time)
But I want to be able to render the datetime or time selects in the user's time zone, yet still save them to the database as UTC. I've been able to achieve this by hard coding it to Easter time by:
- Time.use_zone("Eastern Time (US & Canada)") do
%fieldset.border.border-dark.p-2
%legend Start Time
.input-group
= f.time_select :start_time, {ignore_date: true, minute_step: 15, prompt: true, ampm: true}, {class: "form-select form-select-lg border border-dark ms-2 me-2"}
.text-end.text-muted
= Time.zone
The above code will use Eastern Time (US & Canada) as the time zone the user sees, but at the same time is still saved to the database as UTC.
In order to make this more dynamic, I need to get the client's time zone, which according to this thread, you can obtain the client's IANA time zone by:
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
However, I need a way to post this to the events/new controller so that I can use it as a Ruby instance variable to change one line above:
- Time.use_zone(@my_zone) do
In my Events Controller I currently have:
def new
@my_zone = params[:my_zone]
@my_zone = ActiveSupport::TimeZone[TZInfo::Timezone.get('America/Vancouver').period_for_utc(Time.now.utc).utc_offset]
@event = Event.new
The second time that @my_zone is called, we are using an ActiveSupport that would convert the iANA value directly into the TZInfo value that the Time.use_zone uses, as discussed here.
Then once the controller has that value, it can plug it into Time.use_zone() method.
Getting Javascript to post to the controller is where I'm struggling. I attempted to use a similar AJAX call to this thread, such that at the bottom of my new.html.haml:
:javascript
$.post('/events/new', {my_zone: Intl.DateTimeFormat().resolvedOptions().timeZone}))
However, when I try to run that, the browser console says:
Syntax Error: Bare private name can only be used on the left hand side of an 'in' expression.
I can't figure out what's going on with that.
On the other hand, I'm actually on Rails 7 now, which I do know doesn't have UJS by default but rather uses Stimulus, Hotwire and Turbo. So, is there a way I could do the post to the controller via Stimulus, Hotwire and turbo?