Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format datetime in rails?

Tags:

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
like image 575
sharataka Avatar asked Mar 25 '13 22:03

sharataka


People also ask

How do you parse time in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.


2 Answers

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.

like image 177
weltschmerz Avatar answered Sep 20 '22 19:09

weltschmerz


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] %>
like image 28
Luís Ramalho Avatar answered Sep 17 '22 19:09

Luís Ramalho