Today I Learned

hashrocket A Hashrocket project

The case of meridian in Ruby's strftime

When formatting dates using strftime, you can include AM/PM with %p:

puts Time.now.strftime("%H:%M:%S %p")
# 20:40:52 PM

I didn’t want PM capitalized, so I did this:

puts Time.now.strftime("%H:%M:%S %p").downcase
# 20:40:52 pm

But I found that you can also just use %P:

puts Time.now.strftime("%H:%M:%S %P")
# 20:40:52 pm

Yes that’s right, when you want lowercase AM/PM, use uppercase P. When you want upppercase, use lower. It couldn’t be more straightforward folks.

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.