Format DateTime in Text Box in Rails

前端 未结 7 1825
生来不讨喜
生来不讨喜 2021-01-31 18:59

Is there an easy way to format the display of a DateTime value in a Rails view?

For example, if I\'m doing something like:

<%= text_field         


        
7条回答
  •  一生所求
    2021-01-31 19:37

    This can be handled DRYly at the model layer using the Rails-provided _before_type_cast method variant. Rails already uses this method for doing just this type of formatting, so we're just overwriting the default. For example:

    class MyModel
       def start_date_before_type_cast
          return unless self[:start_date]
          self[:start_date].strftime('%m/%d/%Y')
       end
    end
    

    This way, anywhere you have a text field for the MyModel#start_date field you get formatting for "free".

提交回复
热议问题