Home > Software engineering >  Ruby strftime: don't show minutes if zero
Ruby strftime: don't show minutes if zero

Time:09-21

I'm trying to achieve this style of output:

Time.new(2021,9,19,6,0,0) => "6am"
Time.new(2021,9,19,6,30,0) => "6:30am"

Closest I've gotten is strftime('%l:%-M%P') which yields:

Time.new(2021,9,19,6,0,0).strftime('%-l:%-M%P') => "6:0am"
Time.new(2021,9,19,6,30,0).strftime('%-l:%-M%P') => "6:30am"

Is there a known way to suppress %M or %-M when zero, or am I going to need to do my own thing here?

CodePudding user response:

You might have to do your own thing but this is a simple way to do it.

time.strftime('%-l:%M%P').sub(':00', '')
  • Related