Ruby Date.month with a leading zero

I have an object Datein Ruby.

When I do myobj.month, I receive 8. How to get a month with a leading zero, for example 08.

Same idea with day.

What I'm trying to get at the end 2015/08/05.

+4
source share
1 answer

It is possible to use formatted string output

Examples:

puts sprintf('%02i', 8)
puts '%02i' % 8

%02iis a format for two digits (an integer) with leading zeros. Details can be found in the documentation for sprintf

In your specific case with the date, you can simply use the Time#strftimeod method Date#strftime:

require 'time'
puts Time.new(2015,8,1).strftime("%m")
+5
source

Source: https://habr.com/ru/post/1617892/


All Articles