I’ve been working with the Time class in Ruby today, and I’m finding some “quirks” that I can’t understand. For example, a very simple thing I’m trying to do is to print out the day of a month: let’s say for July 4th, I want “4″. And let’s say my_time is our time variable,
my_time.day
=> 4
my_time.strftime("%d")
=> "04"
my_time.day gives me what I want, but it’s a Fixnum, an integer. To convert it to a string I need to do this,
my_time.day.to_s
That seems roundabout. I prefer strftime, but there isn’t a format specifier for day without leading zeros. Which seems strange to me. In PHP you can use j to get day of the month without leading zeros. Hmm.
Time class in Ruby,
http://www.rubycentral.com/ref/ref_c_time.html
date in PHP,
http://us3.php.net/manual/en/function.date.php
One Comment
Jesse Hallett / 19 December 2006
I realize this comes a bit late, but I have a solution.
strftime allows you to set the column width of a displayed number, which affects the number of leading zeros that are displayed. To do this, place a number between the percent sign and the character code. For example, the formatting string “%5d” adds the required number of leading zeros to the day number to fill out 5 characters.
If you have a preexisting leading zero that you want to get rid of, use a negative number for the column width. To get rid of one zero, use -1. So the formatting “%-1d” displays the day without any leading zeros. Both single and double digit numbers seem to display correctly using this method.
Post a comment