20

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
sharataka
  • 4,922
  • 20
  • 64
  • 119

4 Answers4

32

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.

weltschmerz
  • 12,936
  • 10
  • 60
  • 110
  • Thanks! This and the documentation is super helpful. I haven't been able to find how to convert a time between timezones. In my example, the time is currently in UTC but would like it to show PST. Do you know how I could enable this? – sharataka Mar 25 '13 at 22:36
  • Welcome :) Refer to this: http://stackoverflow.com/questions/6118779/how-to-change-default-timezone-for-activerecord-in-rails3 – weltschmerz Mar 25 '13 at 22:37
9

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] %>
Luís Ramalho
  • 9,535
  • 4
  • 48
  • 66
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

Ashley
  • 2,198
  • 1
  • 31
  • 60
0

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??

stevejpurves
  • 888
  • 1
  • 7
  • 10