Time conversion between ruby on rails and javascript vice versa?

前端 未结 5 1151
遇见更好的自我
遇见更好的自我 2020-12-23 14:06

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

Ruby on rails :

 Time.now

Javascript :

 new Date()
         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-23 15:00

    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
    

提交回复
热议问题