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

To format a date in the format month day, year hour:minute:second am/pm in Ruby, you can use the strftime method which stands for "string format time". strftime takes a format string with various format specifiers that represent different date and time components.

Here's an example code snippet that initializes a DateTime object with the current date and time, and formats it using strftime:

main.rb
require 'date'

now = DateTime.now
formatted_date = now.strftime("%B %d, %Y %I:%M:%S %p")

puts formatted_date # prints something like "May 24, 2021 11:30:00 AM"
162 chars
7 lines

In the strftime format string above, %B represents the full month name, %d represents the day of the month as a zero-padded decimal number, %Y represents the year with century as a decimal number, %I represents the hour (12-hour clock) as a zero-padded decimal number, %M represents the minute as a zero-padded decimal number, %S represents the second as a zero-padded decimal number, and %p represents 'AM' or 'PM' in uppercase.

You can adjust the format string to your desired output.

gistlibby LogSnag