Richlewis
Richlewis

Reputation: 15374

Convert Time to just Number in Ruby

I have a field in my form that is saved in a time format

t.time :time_from

When saving a time it is saved like this in the DB

2000-01-01 18:00:00 UTC

However I would like to display the output as 18:00 in my view. How would I go about converting this using a helper for example?

Do I need to save it in a better format when going in to the DB or will a helper suffice?

Upvotes: 2

Views: 90

Answers (3)

toro2k
toro2k

Reputation: 19228

In Rails you can just use the to_s method that is aliased as to_formatted_s passing the symbol :time as an argument:

Time.now.to_s(:time)
# => "18:11"

Upvotes: 2

xlembouras
xlembouras

Reputation: 8295

I work on a project that must always be internationalized and the use of i18n.l helper has proven to be ideal.

I would recommend it for you case as well, apart from internationalization it is a very efficient way to keep track of used formats throughout the project.

Upvotes: 3

sawa
sawa

Reputation: 168101

Do this:

time.strftime("%H:%M")

Upvotes: 3

Related Questions