How do I format datetime in rails?

39,576

Solution 1

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.

Solution 2

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] %>

Solution 3

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

Share:
39,576

Related videos on Youtube

sharataka
Author by

sharataka

Updated on July 09, 2022

Comments

  • sharataka
    sharataka almost 2 years

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

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

    The result of this line is below:

    2013-02-02 01:00:00 UTC 
    

    How do I change this so it displays as:

    2/2/13: X:00 PST