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.rb190 chars6 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