Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby Date.month with a leading zero

Tags:

datetime

ruby

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.

like image 955
Nathan H Avatar asked Nov 29 '15 11:11

Nathan H


People also ask

What is Strftime in Ruby?

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.

How do I change the date format in Ruby?

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.

How do I remove 0 from a date in python?

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.

What is DateTime in Ruby?

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.


1 Answers

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")
like image 193
knut Avatar answered Sep 19 '22 12:09

knut