0

I'm retrieving data from database in ruby on rails.I have to update the Date retrieved with a new formatted date in controller.
Something like this one:-

   @events = 'My Query.'
   @events.each do |eventdata|
      # Since the date is in utc i have to convert it in users time zone.
      eventdata.start_date = eventdata.start_date.strftime("%Y-%m-%d %H:%M:%S")
    end

But its not working. Need some help on this.

1
  • 3
    It's not working. I see. Commented Dec 7, 2012 at 6:49

2 Answers 2

2

This is a monkey patch to format the date of all the DateTimes when being converted to json:

class ActiveSupport::TimeWithZone
  def as_json(options = {})
      strftime('%Y-%m-%d %H:%M:%S')
  end
end

put that on

/config/initializers/json_date_path.rb

and that's all.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much ... finally got solved ...was working on this from yesterday :)
2

You cannot change the format of the field, its a DateTime, you will have to use a method for that

def formated_start_date
  start_date.strftime("%Y-%m-%d %H:%M:%S")
end

However, you can change the format of the datetimes for all the database records, by creating the file config/initializers/date_time_formats.rb and add some content like

Time::DATE_FORMATS[:default] = "%Y-%M-%d %H:%M:%S"

3 Comments

And how can i update this value ? eventdata.start_date = eventdata.formated_start_date ?... Actually i'm converting that event object to json which is used in calendar and therefore i have to format it in controller.
I need more words about what you are trying to do. What you are trying to do is to format the date before the object is converted to json? Or you are trying to change the way you format the DateTime before it is persisted into the database?
I'm trying to format the date before the object is converted to json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.