Time conversion between ruby on rails and javascript vice versa?

前端 未结 5 1142
遇见更好的自我
遇见更好的自我 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 14:46

    These methods in both are equivalent, use either:

    For Ruby:

    Time.now.httpdate
    

    For Javascript:

    new Date().toUTCString()
    

    Output for both:

    Tue, 04 Jul 2017 14:18:31 GMT
    
    0 讨论(0)
  • 2020-12-23 14:46

    Use strftime to get miliseconds:

    <script>
      date = new Date(<%= DateTime.now.strftime '%Q' %>);
    </script>
    

    And parse back to Ruby using to_date:

    params[:date].to_date
    

    to_date accepts few formats:

    '3-2-2001'
    '03/02/2001'
    '2001-02-03'
    '3rd Feb 2001'
    '20010203'
    
    0 讨论(0)
  • 2020-12-23 14:50

    From jquery to rails:

    "Wed Mar 12 2014 23:45:39 GMT+0530 (IST)".to_time
    
    0 讨论(0)
  • 2020-12-23 14:51

    I think it will help you :

    ruby date to javascript date conversion:

    <script>
      var date_str = <% Date.today %>;
      var date_obj = new Date(date_str);
    </script>
    

    javascript date to ruby date conversion:

    use this code in ruby class.

    fetch date from params attributes.

    date_str = params[:js_date]
    date_obj = Date.parse(date_str)
    

    for more info you can refer:

     http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html
     http://www.w3schools.com/jsref/jsref_parse.asp
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题