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

You can use strftime method of DateTime or Time class to format a date in Ruby:

main.rb
time = Time.now
puts time.strftime("%B %d, %Y %I:%M:%S.%L %p")
63 chars
3 lines

Output:

main.rb
November 20, 2021 11:30:45.953 AM
34 chars
2 lines

Explanation:

  • %B: full month name (e.g. November)
  • %d: day of the month, zero-padded (e.g. 01)
  • %Y: year with century (e.g. 2021)
  • %I: hour in 12-hour clock (e.g. 05)
  • %M: minute of the hour (e.g. 27)
  • %S: second of the minute (e.g. 59)
  • %L: millisecond of the second (e.g. 567)
  • %p: either "AM" or "PM"

You can replace Time.now with your own DateTime or Time object.

gistlibby LogSnag