rails ruby 中使用辅助方法的时间格式

time format using helper method in ruby on rails

我在 table

中归档了时间数据
t.time "start_time"
t.time "end_time"

当我添加数据时,它以这种格式显示

Start Time  2000-01-01 06:00:00 UTC
End Time    2000-01-01 08:00:00 UTC

我只想显示时间?我该怎么做。?

我的表格是这样的

      <div class="form-group row">
         <%= form.label :start_date, class: "control-label text-right col-md-2" %>
         <div class="col-md-4">
           <div class="input-group">
             <%= form.text_field :start_date, id: :course_start_date, value: "#{format_date(form.object.start_date)}", class: "form-control mydatepicker" %>
             <span class="input-group-addon"><i class="icon-calender"></i></span>
         </div>
        </div>
      </div>
      <div class="form-group row">
         <%= form.label :end_date, class: "control-label text-right col-md-2" %>
         <div class="col-md-4">
           <div class="input-group">
              <%= form.text_field :end_date, id: :course_end_date, value: "#{format_date(form.object.end_date)}", class:"form-control mydatepicker" %>
              <span class="input-group-addon"><i class="icon-calender"></i></span>
           </div>
         </div>
      </div>

您可以使用 strftime 来实现。

date.strftime('%H:%M:%S')

尝试 strftime("%I:%M%p")
如需更多信息,请查看 here

使用下面的代码将解决您的问题:

Time.parse(start_time).strftime("%H:%M")

Rails 有 to_formatted_s 辅助方法(别名为 to_s。这个辅助方法已经定义了几种日期和时间格式,很容易定义自己的格式。

你很幸运,因为只返回没有日期信息的时间已经存在:

start_date.to_s(:time)

与直接使用 strftime 相比,在 Rails 中使用命名日期和时间格式的好处在于,以后更改格式要容易得多,因为只有一个地方可以更改。并且您可以定义取决于语言环境的格式。