views:

26

answers:

1

Hi

I have this controller:

class SchedulesController  "post", :except => :index

  def index
    #Schedules.create(:id => -1, :deviceId => "2002", :subject => "Test 2", :scheduleTime => Time.new, :repeatEveryYear => "FALSE")
    #@schedules = Schedules.all
    respond_to do |format|
      format.html # list.html.erb
      format.json { render :json => @schedules.to_json }
    end
  end

  def create
    @schedule = Schedules.new.from_json(params[:schedule])
    @schedule.save
    render :json => "success"
  end
end

The Schedule has a dateTime field, how can I get the controller to return this time formatted as "yyyy-MM-dd HH:mm:zzzz" (zzzz = Specific GMT timezone)?

Thank you Søren

+2  A: 

You can specify the date and time formats in the initializers. For instance, create the file config/initializers/time.rb and put the following code:

Time::DATE_FORMATS[:schedule] = "%Y-%m-%d %H:%M:%z"

Then in your Schedule.rb:

def formatted_schedule_time
  scheduleTime.to_s(:schedule)
end

And every time you call the to_json method on a Schedule object, you need to do:

@schedule.to_json(:methods => [:formatted_schedule_time])
jordinl