Format DateTime in Text Box in Rails

前端 未结 7 1945
生来不讨喜
生来不讨喜 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

    In a helper

    def l(value, options = {})
       return nil unless value.present?
       value = value.to_date if value.is_a? String
       super(value, options)
    end
    

    Then in the view

    <%= f.text_field :end_date, class: "datepicker" :value => l(@activity.end_date) %>
    

    Here l is a rails helper (I18n.l) which can be locale specific and can take a format. Examples:

    l(@activity.end_date, format: :short)
    l(@activity.end_date, format: "%d-%m-%Y")
    

提交回复
热议问题