Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time conversion between ruby on rails and javascript vice versa?

How to convert ruby time to javascript time and vice versa?

Ruby on rails :

 Time.now 

Javascript :

 new Date() 
like image 447
Satishakumar Awati Avatar asked Mar 12 '14 18:03

Satishakumar Awati


2 Answers

Perhaps the most reliable way is to use seconds since the epoch for ruby, and milliseconds for JavaScript.

In ruby:

t = Time.now # => 2014-03-12 11:18:29 -0700 t.to_f * 1000 # convert to milliseconds since 1970-01-01 00:00:00 UTC. # => 1394648309130.185 

This value can be directly given to the JavaScript Date constructor:

var d = new Date(1394648309130.185) d // Wed Mar 12 2014 11:18:29 GMT-0700 (Pacific Daylight Time)  d.getTime() // 1394648309130 (Fractions of a millisecond are dropped) 

The output of d.getTime() divided by 1000 can be given to ruby's Time.at():

Time.at( 1394648309130 / 1000.0 ) # => 2014-03-12 11:18:29 -0700 
like image 161
Matt Avatar answered Sep 19 '22 09:09

Matt


From jquery to rails:

"Wed Mar 12 2014 23:45:39 GMT+0530 (IST)".to_time 
like image 22
Vasu Adari Avatar answered Sep 20 '22 09:09

Vasu Adari