darkginger
darkginger

Reputation: 690

Converting Rails datetime to Javascript Date in milliseconds

There has been some discussion of how it is possible to convert a Rails UTC DateTime into a Javascript date value, like here. However, I am seeing errors when I try to go a step further and make that DateTime dynamic.

In the end, I am trying to make a JS countdown timer that will show the remaining seconds between Time.now (Rails) and a set UTC time called game_start. I am using this scrappy method for passing a Rails object (like a DateTime from a table) into Javascript.

So currently, I am doing the following:

 // This is the scrappy way I am storing a temp value for DateTime
 <%= content_tag :div, class: "temp_information", data: {temp: @tempquiz} do %>
    <% end %>

 <div id="timer"></div>

 <script>
   $(document).ready(function() {
     var dt = $('.temp_information').data('temp');
     alert(dt);
   }); 

This returns a UTC string as an alert, like 2016-02-18T23:07:00.000-08:00. So I am successfully passing that Rails data into JS. T

he issue is when I try to combine it with some Javascript, like:

 $(document).ready(function() {
    var data = $('.temp_information').data('temp');
    var dt = new Date (<%= data.ToJavaScriptMilliseconds() %>);
    alert(dt);
    });

If I am going to make a timer that counts down, I am going to need to capture the game_start time (temp is doing that) and convert it to JS Milliseconds (that is breaking). However, when I do that (code is based on this answer), I get this error:

   undefined local variable or method `data'

I don't get it at all, since I am defining data in the line before within the $(document).ready as the UTC string we saw in the alert. If it knows what data is and can return the alert in the first instance, how is it unable to produce it in the second instance?

Upvotes: 1

Views: 6123

Answers (1)

dre-hh
dre-hh

Reputation: 8044

Passing data to a tag in ruby, will render a data attribute on the html tag. The tag is <div> class='temp_information' data-temp='2016-02-18 09:38:41 +0100' </div> in the above case.

UPDATE: however this is a format which can't be parsed by all browsers. The most reliable method is to convert the time to a unix timestamp.

Also the ISO 8601 format should be supported by all browsers now. This format is used by GitHub Api for example.

The ruby Time object can be converted to javascript date like this

ruby

Time.at(1644394891).to_i
=> 1644394891

require 'time'
Time.at(1644394891).utc.iso8601
=> "2022-02-09T08:21:31Z"

javascript

new Date(1644394891 * 1000)
=> Wed Feb 09 2022 09:21:31 GMT+0100 (CET)

new Date("2022-02-09T08:21:31Z")
=> Wed Feb 09 2022 09:21:31 GMT+0100 (CET)

So for your code it's

new Date($('.temp_information').data('temp'));

you have to call @tempquiz.utc.iso8601 before rendering

Upvotes: 3

Related Questions