When using a Ruby / Rails based API, you often need to deal with dates in a coherent manner. Say I have a model called Post which looks like the following:
def self.up
create_table :posts do |t|
t.string :title
t.text :message
t.timestamps
end
end
If you’ve been coding in Rails for any length of time, you know that t.timestamps simply creates our created_at and updated_at fields on our model, which are handled without our intervention 99% of the time. But what happens when you have an AJAX-ified user interface, or your passing data to a mobile application, or your using a Node.js application to parse the data and publish it somewhere? Ruby dates and JS Dates and theres no way to directly parse between them.
A javascript date can look like this:
var d = new Date();
>>returns Thu Sep 01 2011 09:47:01 GMT-0400 (EDT)
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
But a Ruby date looks like this:
d = new DateTime()
>> returns Mon, 01 Jan -4712 00:00:00 +0000
Now one way of doing this is to use a d.strftime() call to format it in a Javascript parse-able manner. Much quicker though, is to use the numerical version of the number.
Ruby:
@post = Post.first
"returns first post object"
@post.created_at
>> returns Thu, 01 Sep 2011 09:50:12 -0400
@post.created_at.to_i
>> returns 1314885012
@post["created_at_in_secs"] = @post.created_at.to_i
Now I pass back in my params to the AJAX call (usually as JSON) and can quickly parse it in Javascript
JS:
var postSeconds = < %= @post["created_at_in_secs"] %>
var d = new Date(Number(postSeconds) * 1000);
>> returns Thu Sep 01 2011 09:50:12 GMT-0400 (EDT)
