Jump to content

The ultimate community for Ruby on Rails developers.


Photo

[Share] How to : Remove Leading Zero on strftime function

leading zero strftime

  • Please log in to reply
2 replies to this topic

#1 Kevin

Kevin

    Signalman

  • Members
  • 21 posts

Posted 14 August 2013 - 11:54 PM

strftime is one of Ruby DateTime function that will enable you to formats date according to directives of given format String. This function , according to the documentation, existed since Ruby 1.8.6. And this function still existed on Ruby latest stable version : 1.9.3. As you can see on the documenation (or you may already have used it), the directives for Hour, Month and others will add leading zero to the result. For example, if you use :

strftime('%I') #Hour of the day, 12-hour clock (01..12)

You'll get 01,02,03,..12 (depending on the DateTime you passed). How to get 1,2,3,4,..12 (without leading zero) ?

It's true if you need to get day of the Month without leading zero, you can use %e (as mentioned on the documentation, instead of using %d). Unfortunately, I can't find such function to get Hours without leading zero. Therefore, after doing a little experiment, I found that adding a - after % will remove leading zero.

strftime('%-I') #Hour of the day, 12-hour clock (1..12) - without leading zero
strftime('%-H') #Hour of the day, 24-hour clock (1..24) - without leading zero


 
So, we don't need to develop our own function just to format date or time without leading zero.
 
 
Source of this post :


#2 Ohm

Ohm

    Guard

  • Members
  • 179 posts
  • LocationCopenhagen

Posted 15 August 2013 - 06:32 PM

I never thought of this as a problem.

If you want to, you can blank pad the values with 

DateTime.parse("2013-08-15 08:15").strftime("%k") # => " 8"

From the Ruby docs (http://www.ruby-doc....strftime-method)


Blog: http://ohm.sh | Twitter: madsohm


#3 Kevin

Kevin

    Signalman

  • Members
  • 21 posts

Posted 21 November 2013 - 08:38 AM

I never thought of this as a problem.

If you want to, you can blank pad the values with 

DateTime.parse("2013-08-15 08:15").strftime("%k") # => " 8"

From the Ruby docs (http://www.ruby-doc....strftime-method)

yeah, depending on the business requirement you're working on.






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users