最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Rails 3 Date to UTC for use in javascript - Stack Overflow

programmeradmin1浏览0评论

I have a date type field, 2011-07-20 as a format example, that I need to convert to UTC for use in javascript. I know I can use Date.UTC in javascript but then the month is off by one and it doesn't take the dashes as delimiters.

How do you convert the default rails date format to UTC?

I have a date type field, 2011-07-20 as a format example, that I need to convert to UTC for use in javascript. I know I can use Date.UTC in javascript but then the month is off by one and it doesn't take the dashes as delimiters.

How do you convert the default rails date format to UTC?

Share Improve this question edited Aug 30, 2011 at 0:21 Xaxum asked Aug 29, 2011 at 23:10 XaxumXaxum 3,6759 gold badges47 silver badges66 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 13

In a controller

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

In a view

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

Just to add another option (derived from kreeks' answer):

You can monkey-patch the Time class in an initializer to add a to_js method:

 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.

Suppose you have a string '2011-07-20', the following should help

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

The above answers did not work for me as I found that I was getting a mismatch with timezones. For the following date in javascript (note month is zero-indexed in js)

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

to get the identical value in Ruby I did this:-

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

Then to verify 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());
发布评论

评论列表(0)

  1. 暂无评论