I have a Date
object in Ruby.
When I do myobj.month
I get 8
. How do I get the date's month with a leading zero such as 08
.
Same idea with day
.
What I am trying to get at the end is 2015/08/05
.
Ruby | Time strftime() function Time#strftime() is a Time class method which returns the time format according to the directives in the given format string. Syntax: Time.strftime() Parameter: Time values. Return: time format according to the directives in the given format string.
You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.
If you add a hyphen between the % and the letter, you can remove the leading zero. For example %Y/%-m/%-d. This only works on Unix (Linux, OS X), not Windows. On Windows, you would use #, e.g. %Y/%#m/%#d.
Ruby | DateTime new() function DateTime#new() : new() is a DateTime class method which returns a DateTime object denoting the given calendar date. Return: a DateTime object denoting the given calendar date.
There is the possibility of using a formated string output
Examples:
puts sprintf('%02i', 8)
puts '%02i' % 8
%02i
is the format for 2 digits width integer (number) with leading zeros.
Details can be found in the documentation for sprintf
In your specific case with a date, you can just use the Time#strftime
od Date#strftime
method:
require 'time'
puts Time.new(2015,8,1).strftime("%m")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With