Ruby datetime: Manipulating Time and Dates Made Simple

rubyRuby is an object-oriented programming language inspired by Eiffel, Lisp and, to a large degree, Perl. You should learn Ruby before you learn Perl, because it is much easier to to learn and write code in. You can use Ruby for a variety of purposes like creating your own applications and to design your own graphical user interface (GUI).

If you don’t have Ruby installed, you can download it for free from the official website. Ruby is fairly draining on your system if it’s used for heavy tasks, so you should have at least 2GB of RAM installed and your PC should have the latest processor if possible.

Ruby Basics

In this tutorial, you’re going to learn how to utilize system data and time in your program. We’re assuming you’re familiar with how to create classes and objects in Ruby. If you are, you can skip the following section of the article. If you’re not familiar with how to create an object in Rub, read on:

Ruby is very similar to other programming languages like Java and C++. If you know how to create an object in Java, you should have no problem creating an object in Ruby. To create a class in Ruby, we use the following syntax:

class name_of_class
end

To create an object of a class, we use the “new” keyword, just like in Java. The syntax to create an object in Ruby is:

object_name = name_of_class.new

Now that you know how to create objects and classes in Ruby, we can move on to date and time formatting.

Ruby Date and Time

Ruby incorporates three library classes with which we can handle date and time. The time class (which we’ll be using for this tutorial) is from the time library, while the date and datetime classes are from the date library. The Time class is usually sufficient for your everyday programming needs. However, because the class is based on the time provided by your operating system, it may not be able to display dates before the year 1970 and after the year 2038.

Current Date and Time

You can ask Ruby to retrieve current system date and time and print it for you:

#!/usr/bin/ruby -w
time = Time.new
puts "Current Time : " + time.inspect

This gives the following output:

Current Time: Tue Dec 24 7:50:00 -0700 2013

Explanation: Here we have declared “time” as an object of the “Time.new” class which is already defined in the system. We are asking Ruby to display the current time with the “puts”command.

Isolating Sections of Time

We can ask Ruby to retrieve specific parts of time, like the year, month and day. Let’s assume we have created an object “time”, like we did in the example above:

#!/usr/bin/ruby -w
time = Time.new

To get current year, we can use the code:

puts time.year              
#this prints 2013

For month:

puts time.month          
#this prints 12 (Months are sorted from 1 to 12)

For day of the week:

puts time.wday                
#this prints 2 (Days are sorted from 0 to 6, where 0 is Sunday)

For the date of the month

puts time.day                
#this prints 24 (Displays calendar date of the day)

For hour:

puts time.hour              
#this prints: 08:00 (24 hour format)

For minute:

puts time.minute         
#this prints: 08.01

For seconds:

Puts.time.sec                
#this prints: 50

For microseconds (000000-999999):

puts.time.usec              
#this prints: 344012

For time.zone:

puts time.zone                             
#this prints: UTC

For the current day number, out of 365 days in a year:

puts time.yday              
#this prints: 358

Playing With Time

Now that you know how to display time on screen, you can begin to manipulate it. Ruby allows you to format time as you please. First, let’s take a simple example on how to manipulate time:

timenow = Time.timenow        #we create an object called timenow
puts timenow
futuretime = timenow + 30      #we add 30 seconds to our current time
puts futuretime
pastime = timenow -30                              #we subtract 30 seconds from our current time
puts pastime

Output:

Tue Dec 24 7:50:00 -0700 2013
Tue Dec 24 7:50:30 -0700 2013
Tue Dec 24 7:49:30 -0700 2013

Formatting System Time and Date

You can format the system date using the “strftime(“year-month-date” “Hours:Minutes:Seconds”)” method. For example:

#!/usr/bin/ruby -w
time = Time.new
puts +time.inspect
puts time.strftime (“2014-12-24” “09:21:00”)

Output:

    Tue Dec 24 7:50:00 -0700 2013
    2014-12-24 09:21:00

As you can see, with the strfttime method, we changed the current time and date to another format. Strftime actually converts whatever data we specify as a string to the date format we want.

Creating an Object with a Specific Date

You can create an object in Ruby that stores the value of any date you want. We can use the DateTime class for this:

DateTime.new (2013, 12, 24, 8, 21, 0, ‘+5’)

The output would be: 2013-12-24 T 08:21:00+05:00

Special Helper Methods in Ruby

Ruby provides some very useful methods with which you can retrieve the time at the beginning of the day, end of the day, a day ago, a month ago and even years ago.

If you want to find what the time was a day ago, you would use the method:

1.days.ago    

If you want to know how many seconds are left until midnight, you can use the method:

.seconds_until_end_of_day ()

If you want to know how many seconds have passed since midnight the current day, use the method:

.seconds_since_midnight ()

Some of the other useful methods you may want to try are at_end_of_day(), at_end_of_minute(), at_beginning_of_day() and at_midnight ().

Remember that these methods have to be used with objects. You can check other methods that can be coupled with objects to display other data related to time. To learn more you can look up our advanced Ruby course.

Remeber, to master Ruby programming, or any programming language, it’s important that you practice as much as possible!