Time and Date Formatting

Ruby has some great features for working with dates and times.

The Basics

time = Time.now #returns the time today
time = Time.new( 2017, 10, 01, 2, 2, 2) # returns the time on Oct 1st 2017 at 02:02:02 AM

time.monday? #=> false
time.year #=> 2017

time = time + 2.days  # returns Oct 3rd 2017 at 02:02:02 AM

Neat! and there’s lots more

time = Time.new

## Components of Time

puts "Current Time : " + time.inspect
puts time.year    # => Year of the date 
puts time.month   # => Month of the date (1 to 12)
puts time.day     # => Day of the date (1 to 31 )
puts time.wday    # => 0: Day of week: 0 is Sunday
puts time.yday    # => 365: Day of year
puts time.hour    # => 23: 24-hour clock
puts time.min     # => 59
puts time.sec     # => 59
puts time.usec    # => 999999: microseconds
puts time.zone    # => "UTC": timezone name

time.zone       # => "UTC": return the timezone
time.utc_offset # => 0: UTC is 0 seconds offset from UTC
time.zone       # => "PST" (or whatever your timezone is)
time.isdst      # => false: If UTC does not have DST.
time.utc?       # => true: if t is in UTC time zone
time.localtime  # Convert to local timezone.
time.gmtime     # Convert back to UTC.
time.getlocal   # Return a new Time object in local zone
time.getutc     # Return a new Time object in UTC

But printing the time out and giving a nice readable format to a user would be lovely. We can use to_s but we get something like this

Tues Oct 03 02:02:02 -0500 2017

That is not human-friendly and certainly not pretty!

Date formatting

Would it be useful if you could customise how a date is presented. Guess what. You can!

There’s a method called strftime that allows you to provide a date formatter and Ruby will automatically spit out the date, time or any combinaiton of it’s parts in whatever format you want.

puts time.strftime("%Y-%m-%d %H:%M:%S")
# gives: 2017-10-01 02:02:02

puts time.strftime("%A %B %d, %Y %H:%M")

# gives: Tuesday October 01, 2017 02:02


puts time.strftime("%B %Y")
# gives: October 2017


Perfect!

It’s a really flexible and powerful way to cusotmier your dates…. But how do you rememebr the syntax. Thankfully you don’t have to

Helpful tool: http://strftime.net/

Just visit http://strftime.net/. This is a great website that allows you to intuitively build your custom ‘strftime’ date responses which you can then copy and paste into your code.

×

Subscribe

The latest tutorials sent straight to your inbox.