Quick json question..

How does one format a time when serializing an active record object? Server side somehow or leave it up to client side javascript?

-tim

Yeah.. I was basically wonder what the best practice / preferred method for this was.

When using ajax and json to update a page with a new object that includes a date.. (like created_at) and you want that date to be only month and day.. Do you parse the date on the server side and send over as string (Is that possible with to_json?) or do you send over the default ISO format and do the conversion on the client side in javascript.

I'd like to do it on the server side, but then the only way I can see is a complete hack around by adding another method to the ActiveRecord class.

def created_at_formatted self.created_at.to_S('md') end

object.to_json( :methods => [:created_at_formatted] )

-tim

That is why I mentioned it was a hack..

I take it there is no way to do it via the to_json method which is the view at this point?

Thanks.. -tim

Tim W. wrote:

That is why I mentioned it was a hack..

I take it there is no way to do it via the to_json method which is the view at this point?

Given that JSON offers no data type for storing date and time information, a choice must be made. Rails core team, I believe smartly, decided to borrow the string representation of time from XML, which does define standard date and time representations.

I would not call this a view. In the same way as databases store representations of the data, so does the serialized string of JSON or XML.

What I was getting at in my previous reply was that regardless of how the data is actually stored in a data model (whether that be in model objects, a database or a serialized string) it is still the responsibility of the view layer in MVC to format the data for presentation to the user.

Even though the serialized date may be stored as "2009-08-19T13:03:07Z" you probably would not want to present that to the end user. They would probably prefer something based on their own locale. In the US that might be: "August 19, 2009 9:00 AM" or in Europe maybe something like "19 August 2009 09:00." If I'm not mistaken you can use I18n (Internationalization) in Rails to format dates based on the user's locale.

Given that JSON (or XML) are not what you present to end users, you would store the date and time in a way meaningful to your model. Only when you present that data to a human do you run the data through formatters for presentation.