format a date in to the format month day, year hour:minute:second.fff am/pm zzz in ruby

You can use strftime method to format the date in your desired format. Here's an example:

main.rb
date = DateTime.now
formatted_date = date.strftime("%B %d, %Y %I:%M:%S.%L %p %Z")
puts formatted_date
102 chars
4 lines

This will output something like January 01, 2022 12:00:00.000 AM EST, where:

  • %B stands for full month name
  • %d stands for day of the month with leading zeros (01-31)
  • %Y stands for year with century
  • %I stands for hour in 12-hour format with leading zeros (01-12)
  • %M stands for minute with leading zeros (00-59)
  • %S stands for second with leading zeros (00-59)
  • %L stands for millisecond with leading zeros (000-999)
  • %p stands for AM/PM designation
  • %Z stands for timezone abbreviation

You can change the order of these elements and add other text as needed to make the date look exactly as you want.

gistlibby LogSnag