To format a date into the format month day, year hour:minute am/pm
in Ruby, you can use the strftime
method provided by the DateTime class.
Here's the code that demonstrates how to use strftime
to format the date:
main.rb178 chars4 lines
In the code above, we first get the current date and time using the DateTime.now
method. Then, we use the strftime
method to format the date according to the specified format string.
The format string consists of formatting directives that start with a percent sign (%). In this case, we're using the following directives:
%B
: Full month name (e.g. "January")%e
: Day of the month, with leading zero (01..31)%Y
: Year (e.g. 2021)%l
: Hour of the day, 12-hour clock (1..12)%M
: Minute of the hour (00..59)%p
: "AM" or "PM" (uppercase)The result of strftime
is a formatted string that represents the date in the specified format. Finally, we output the formatted date using the puts
method.
gistlibby LogSnag