简体   繁体   中英

time format using helper method in ruby on rails

I have time data filed in my table

t.time "start_time"
t.time "end_time"

and when I add the data it displays in this format

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

I want only time to be displayed? How do I do that.?

my form is like this

      <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')

Try to strftime("%I:%M%p")
And for more information look here

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

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

Rails has the to_formatted_s helper method (which is aliased to to_s . This helper method has several date and time formats already defined and it is easy to define own formats.

You are lucky because returning just the time without date information already exists:

start_date.to_s(:time)

The benefits of using named date and time formats in Rails over using strftime directly are that it makes it much easier to change formats later on because there is only one place to change. And that you can define formats that are depending on a locale.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM