Rails 3 UTC Date for use in javascript

I have a date type field, 2011-07-20 as an example of a format that I need to convert to UTC for use in javascript. I know that I can use Date.UTC in javascript, but then the month is disabled by one, and it does not accept dashes as separators.

How to convert default date format to UTC?

+5
source share
4 answers

In the controller

@time = Time.parse('2011-07-20').utc.to_i*1000

In view

<script type="text/javascript">
    var date = new Date(<%= @time %>);
    alert(date);
</script>
+13
source

Just add one more option (obtained from screaming response):

You can defuse the Time class in the initializer to add a method to_js:

 class ::Time
   def to_js
     self.utc.to_i*1000
   end
 end

and then use this function in your JavaScript:

 var date = new Date(<%= Time.parse('2011-07-20').to_js %>);
 console.log(date);

Hope this helps.

+4

, '2011-07-20',

Time.parse('2011-07-20').utc
+1

The above answers did not help me as I found that I am getting a mismatch with time zones. For the next date in javascript (month zero indexed notes in js)

var date1 = Date.UTC(2014, 0, 1)

to get an identical value in Ruby, I did the following: -

t = Date.new(2014,01,01).to_time
t += t.utc_offset
@timestamp1 = (t.to_i * 1000)

Then for checking in js

var timestamp1 = <%= @timestamp1 %>;
var timestamp2 = Date.UTC(2014, 0, 1);
var date1 = new Date(timestamp1);
var date2 = new Date(timestamp2);
$("#div1").text("Ruby => " + date1.toUTCString() + ', Tz offset =>' +  date1.getTimezoneOffset());
$("#div2").text("JS => " + date2.toUTCString() + ', Tz offset =>' +  date2.getTimezoneOffset());
+1
source

All Articles