Ruby Time formatting and datetime SQL Column

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

VN:F [1.9.22_1171]
Rating: 5.0/5 (1 vote cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
Ruby Time formatting and datetime SQL Column, 5.0 out of 5 based on 1 rating
Facebook Twitter Email

Leave a Reply