How do I format datetime in rails?

前端 未结 4 1501
无人共我
无人共我 2021-02-05 08:51

In my Rails view, I have the below code that displays a datetime.

<%= link_to timeslot.opening, [@place, timeslot] %> 

The result of this

相关标签:
4条回答
  • 2021-02-05 09:34

    to get the precise date formatting that you are looking for in your example use the following strftime format string "%-d/%-m/%y: %k:00 PST"

    However, that may not be exactly what you want.Please clarify in your question (a) what you want to do with the time field (e.g. are you always wanting to display a time on the hour? X:00) and (b) are you always wanting to report PST times or do you want to print the actual timezone, or do you want to convert to PST??

    0 讨论(0)
  • 2021-02-05 09:36

    For the format you have requested:

    <%= link_to timeslot.opening.strftime(%d/%m/%y: %H:%M:%S %Z), [@place, timeslot] %>
    

    More options available here:

    http://rorguide.blogspot.co.uk/2011/02/date-time-formats-in-ruby-on-rails.html

    0 讨论(0)
  • 2021-02-05 09:37

    Use ruby's strftime() on dates/datetimes:

    <%= link_to timeslot.opening.strftime("%Y %m %d"), [@place, timeslot] %>
    

    Have a look at the documentation to find out how the formatting works.

    0 讨论(0)
  • 2021-02-05 09:50

    You should use a helper for this.

    If you want to convert from UTC to PST you can use the in_time_zone method

    def convert_time(datetime)
      time = Time.parse(datetime).in_time_zone("Pacific Time (US & Canada)")
      time.strftime("%-d/%-m/%y: %H:%M %Z")
    end
    
    <%= link_to convert_time(timeslot.opening), [@place, timeslot] %>
    
    0 讨论(0)
提交回复
热议问题