format a date in to the format 'yyyy-mm-dd hh:mm:ss.fff' in ruby

To format a date in the yyyy-mm-dd hh:mm:ss.fff format, you first need to have a DateTime object. Here's an example of how to create a DateTime object from a string:

main.rb
require 'date'

date_string = '2021-10-07'
date = DateTime.parse(date_string)
78 chars
5 lines

Once you have a DateTime object, you can use the strftime method to format it in the desired format. Here's an example:

main.rb
formatted_date = date.strftime('%Y-%m-%d %H:%M:%S.%L')
puts formatted_date  # Output: "2021-10-07 00:00:00.000"
112 chars
3 lines

In this example, %Y represents the year with century, %m represents the month (01 to 12), %d represents the day of the month (01 to 31), %H represents the hour (00 to 23), %M represents the minute (00 to 59), %S represents the second (00 to 59), and %L represents the millisecond (000 to 999).

Note that the millisecond precision may vary depending on the platform and Ruby version.

gistlibby LogSnag