How to format a date using different formats in Ruby

1 Answer

0 votes
require "date"

# Current date and time
now = Time.now

puts "Original time: #{now}\n\n"

# --- BASIC COMPONENTS ---

puts "Year (4 digits): #{now.strftime("%Y")}"      
puts "Year (2 digits): #{now.strftime("%y")}"     

puts "Month (01-12): #{now.strftime("%m")}"       
puts "Month name (short): #{now.strftime("%b")}"  
puts "Month name (full): #{now.strftime("%B")}"   

puts "Day of month: #{now.strftime("%d")}"        
puts "Day of week (short): #{now.strftime("%a")}"  
puts "Day of week (full): #{now.strftime("%A")}"   

# --- COMMON FULL FORMATS ---

puts "YYYY-MM-DD: #{now.strftime("%Y-%m-%d")}"
puts "DD/MM/YYYY: #{now.strftime("%d/%m/%Y")}"
puts "MM-DD-YYYY: #{now.strftime("%m-%d-%Y")}"

puts "YYYY/MM/DD HH:MM:SS: #{now.strftime("%Y/%m/%d %H:%M:%S")}"

# --- TIME FORMATS ---

puts "24-hour time: #{now.strftime("%H:%M:%S")}"
puts "12-hour time: #{now.strftime("%I:%M:%S %p")}"

# --- HUMAN-READABLE TEXT FORMATS ---

puts "Full readable date: #{now.strftime("%A, %B %d, %Y")}"
puts "Full date + time: #{now.strftime("%A, %B %d, %Y %H:%M:%S")}"

# --- WEEK / YEAR INFO ---

puts "Day of year: #{now.strftime("%j")}"   # 001–366
puts "Week number (Sunday start): #{now.strftime("%U")}"
puts "Week number (Monday start): #{now.strftime("%W")}"

# --- ISO / RFC STANDARDS ---

puts "ISO 8601: #{now.iso8601}"

# --- CUSTOM WITH TIMEZONE ---

puts "With timezone: #{now.strftime("%Y-%m-%d %H:%M:%S %Z")}"



=begin
run:
 
Original time: 2026-05-20 16:03:33 +0000

Year (4 digits): 2026
Year (2 digits): 26
Month (01-12): 05
Month name (short): May
Month name (full): May
Day of month: 20
Day of week (short): Wed
Day of week (full): Wednesday
YYYY-MM-DD: 2026-05-20
DD/MM/YYYY: 20/05/2026
MM-DD-YYYY: 05-20-2026
YYYY/MM/DD HH:MM:SS: 2026/05/20 16:03:33
24-hour time: 16:03:33
12-hour time: 04:03:33 PM
Full readable date: Wednesday, May 20, 2026
Full date + time: Wednesday, May 20, 2026 16:03:33
Day of year: 140
Week number (Sunday start): 20
Week number (Monday start): 20
ISO 8601: 2026-05-20T16:03:33+00:00
With timezone: 2026-05-20 16:03:33 UTC
 
=end

 



answered 6 hours ago by avibootz
...