×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby program to demonstrate the time arithmetic

Last Updated : December 15, 2025

Problem Solution

In this program, we will get the current date-time then we will add, remove seconds from the current time and print the result.

Program/Source Code

The source code to demonstrate time arithmetic is given below. The given program is compiled and executed successfully.

# Ruby program to demonstrate time arithmetic

currentTime = Time.now;
print "Current time    : ",currentTime,"\n";

pastTime = currentTime - 20;
print "Past time       : ",pastTime,"\n";

futureTime = currentTime + 20;
print "Future time     : ",pastTime,"\n";

timeDiff = futureTime - pastTime;
print "Time difference : ",timeDiff, " seconds";

Output

Current time    : 2022-02-08 08:36:32 +0000
Past time       : 2022-02-08 08:36:12 +0000
Future time     : 2022-02-08 08:36:12 +0000
Time difference : 40.0 seconds

Explanation

In the above program, we created the object of the Time class. Then we get the current date-time using Time.Now() method. After that, we performed arithmetic operations with the current time and printed the result.

Ruby Date and Time Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.