Undocumented strftime directive

So, you’ve got to display a clearly readable datetime. You might put something like this in your environment.rb file:


[Time::DATE_FORMATS].each{ |format| format.update(:slashes_with_time => '%m/%d/%Y %I:%M %p') }

That works, but it produces an hour with leading zeroes, which is a little less readable for most people. When you search through the docs for strftime, you might think you’ll need to resort to String manipulation to get rid of the leading zero. But there’s a nice AFAICT undocumented strftime directive that’ll do the trick for you: %l (lowercase L).


[Time::DATE_FORMATS].each{ |format| format.update(:slashes_with_time => '%m/%d/%Y %l:%M %p') }

Now, you just use it like this:

my_datetime.to_s(:slashes_with_time)
=> “10/15/2007 3:48 PM”

There’s an extra space there between the date and time, but I can live with that.

2 Comments »

  1. tjstankus said

    Actually, this simplifies the environment.rb code:

    Time::DATE_FORMATS[:slashes_with_time] = ‘%m/%d/%Y %l:%M %p’

  2. Jared said

    I just found this the other day myself, because I needed both a day of the month with no leading zero and an hour with no leading zero. Since I didn’t see it mentioned in your post, the code for day of the month with no leading zero is %e.

    This gives you December 6 (“%B %e”) instead of December 06 (“%B %d”).

RSS feed for comments on this post · TrackBack URI

Leave a Comment