format a date in to the format october 13, 2014 11:13:00.000 am gmt-07:00 in ruby

You can use the strftime method in Ruby's DateTime class to format a date and time object into a string with a custom format. To include the time zone offset, you'll need to use the strftime format %z. Here's an example:

main.rb
require 'date'

dt = DateTime.new(2014, 10, 13, 11, 13, 0, '-07:00')
formatted = dt.strftime('%B %d, %Y %I:%M:%S.%L %p GMT%z')
puts formatted #=> "October 13, 2014 11:13:00.000 AM GMT-0700"
190 chars
6 lines

In this example, we create a new DateTime object with the DateTime.new constructor and pass in the year, month, day, hour, minute, second, and time zone offset values. We then call strftime on this object, passing in the desired format string, which includes placeholders for the month (%B), day (%d), year (%Y), hour (%I), minute (%M), second (%S), millisecond (%L), AM/PM indicator (%p), and time zone offset (%z). The resulting formatted string is assigned to the formatted variable and output to the console.

If you want to display the time zone abbreviation instead of the numeric offset (e.g. "PDT" instead of "-0700"), you can use the %Z format instead of %z. However, keep in mind that this may not work for all time zones, as some do not have a specific abbreviation.

gistlibby LogSnag