Convert Dates Between Ruby and Javascript


Programming in Ruby tutorials and examples

Convert Dates Between Ruby and Javascript

MaxCDN Content Delivery Network

This is a quick overview on how to convert dates between Ruby and Javascript.

Firstly lets tackle the Ruby to Javascript conversion.

Your Ruby Time object needs to be converted into a timestamp which can be done by calling the to_i method. This gives you the integer representation of the full date and time.

  Ruby: Time.now.to_i

Once your Javascript code has access to the timestamp it can be converted to a Javascript date object by passing the integer representation of the Ruby time object to Javascripts date constructor and then multiplying it by 1000.

  Javascript: new Date(timestamp * 1000)

It is also possible to convert Javascript date objects back to Ruby time objects.

By placing the plus operator in front of the Javascript date object it coerces it into number which then needs to be divided by 1000. This gives you the timestamp representation of the Javascript date object

  Javascript: +new Date() / 1000

Your javascript timestamp can then be converted back to a Ruby time object by passing the timestamp (integer) to the Time.at method.

  Ruby: Time.at(your_javascript_timestamp)

All in all this is the simplest and most reliable way I have found to do send dates back and forwards between between both languages.