If you’d like to format Time in Ruby, keep in mind that datetime SQL Columns translate to Time objects.
So you can use the strftime method of the Time class to format the date/time.
For example, assume scheduled_time is a field in your database and it has a sql data type of ‘datetime’.
In your rails model, for example, you can write a method like the following, which will allow you to print out a cleaner format of the date stored in the database which will look similar to 08/31 05:40PM PT. Before modifying the format of the date and time, it probably looked something like: Mon Aug 31 16:05:00 -0700 2009:
Here is a working example sample code:
class SomeModel < ActiveRecord::Base ... def month_day_time scheduled_time.strftime("%m/%d at %I:%M%p PT") end ... end
If you want to remove the leading zeros from the hour or month for example, you can do the following instead:
class SomeModel < ActiveRecord::Base ... def month_day_time_removed_leading_zeros scheduled_time.strftime(" %m/%d at %I:%M%p PT").gsub(/ 0(\d\D)/, ' \1').strip end ... end
For other formatting options, see strftime formatting options
Leave a Reply