Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ruby strftime without leading zeros (See related posts)

Date.today.strftime('%b %d, %Y').gsub(/ 0(\d\D)/, ' \1')


Um... strike that. Seems %e does it without the extra work. Thanks Peter!

Comments on this post

peter posts on Nov 03, 2006 at 05:09
I think %e instead of %d does that for you.
peter posts on Nov 03, 2006 at 05:09
See http://uk.php.net/strftime
timmorgan posts on Nov 03, 2006 at 14:09
Genius! I didn't see that in the Pickaxe.
peter posts on Nov 03, 2006 at 18:50
strftime format is pretty standard across languages, and I tend to use the PHP docs for this one case (mostly because they're the most complete I've found)
orangechicken posts on May 04, 2007 at 20:34
%e gets rid of the zero, but still pads it with a space (as the PHP docs say and confirmed with irb). You'll need to use a similar gsub to get rid of the space.
orangechicken posts on May 04, 2007 at 20:40
And there doesn't seem to be an equivalent for getting the month number without 0-padding. So, to get the fairly common date format of 5/4/07, I believe you have to do this:
Date.today.strftime('%m/%d/%y').gsub( /0?(\d)\/0?(\d)\/(\d{2})/, '\1/\2/\3' )


Anybody have something simpler?
bjhess posts on Aug 17, 2007 at 14:32
You may also wish to make:

08/03/07-01:30


Become:

8/3/07-1:30


Expanded from orangechicken's version:

Time.now.strftime('%m/%d/%y-%I:%M').gsub(/0?(\d)\/0?(\d)\/(\d{2})-0?(\d)/,'\1/\2/\3-\4')
bjhess posts on Aug 17, 2007 at 15:16
Actually, orangechicken, what you have will not work for a date like "04/12/07". Your regex will result in "04/12/07". I think the second digit check needs to look for 1 or 2 digits, ala:

"04/12/07".gsub(/0?(\d)\/0?(\d{1,2})\/(\d{2})/,'\1/\2/\3')


So my example above would be something like:

Time.now.strftime('%m/%d/%y-%I:%M').gsub(/0?(\d)\/0?(\d{1,2})\/(\d{2})-0?(\d)/,'\1/\2/\3-\4')
tharrison posts on Jan 05, 2008 at 17:40
Am I crazy, or does the %e not work in Ruby?

irb(main):001:0> t= Time.now
=> Sat Jan 05 17:39:00 -0500 2008
irb(main):002:0> t.strftime("%e") #Doesn't work
=> ""
irb(main):003:0> t.strftime("%d") #Does work
=> "05"


Is this a php-only thing?

Tom
tharrison posts on Jan 05, 2008 at 17:49
Ok, well it looks like Ruby makes it easier (but not very consistent)

Time.now.day
does the trick. Doh.
peter posts on Jan 05, 2008 at 20:50
Works fine for me, tharrison:

>> t = Time.now
=> Sun Jan 06 01:49:12 +0000 2008
>> t.strftime("%e")
=> " 6"
>> t.strftime("%d")
=> "06"

This is on Ruby 1.8.

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts