How Can I Use Javascript To Get The Local Time In A Rails Form?
Solution 1:
I'd think this would suffice:
= simple_form_for @link do |f|
...
= f.text_field :local_client_time # This generates someunique ID I believe. Otherwise, defineone yourself: id: <your-id>
# javascript
var localTime=newDate();
$('<ID generated through rails for your field>').val(localTime);
Rails will receive this additional parameter on the server side as long as it is part of the form. What you need to do is either add a parameter on your Active Record model class (for instance local_client_time
), and then ensure that is allowed through your strong parameter filter (if you're using Rails 4).
If you have a field on your Active Record model, then Link.new(params[:link]
) should do the trick, otherwise you need to define a method (def local_client_time=
) on your model, which will then handle the input.
Surely there will be some Date management server side as well, but that shouldn't be too problematic.
Solution 2:
Solved this awhile back for my app, there are quite a few different implementations with user Timezones and it can get really way over one's head and daunting to test. I'll post links at bottom for places to see other implmntations.
For your direct request, there is a nice gem that provides the js functionality to detect client's timezone. Refer this
Once setup, you can do something like:
$(function() {
var detected_zone = Temporal.detect();
$('#user_time_zone').val(detected_zone.timezone.name);
});
Once you have the timezone set, you can just use Time.zone.now to get the local time.
Have a look at the Railscasts on how to keep track of each individual user's timezones in the db: link
Post a Comment for "How Can I Use Javascript To Get The Local Time In A Rails Form?"