ruby can display date and time. In this article you will learn how to deal with date and time in ruby.

Date is default, but time cannot go back earlier than 1970. Why? that’s when the logic was added to computers.

Download Free Ruby Ebook

Date and time in ruby

Example

The program below is an example of date and time in ruby. The formatting is explicitly defined (%y for year, %m for month etc).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/ruby -w

time = Time.new

print "Date : "
puts time.strftime("%Y-%m-%d")

print "Time : "
puts time.strftime("%H:%M:%S")

# others:
# %A full weekday name (Monday)
# %a short weekday name (Mon)
# %b short month name (Jan)
# %B full month name (January)
# %j day of the jear (001.. 366)
# %U week number, from sun
# %W week number of current year, from mon
# %w day of the week

The code above displays the date and time. You can use an alternative formatting if you want..
The output will be similar to this:

1
2
Date : 2018-06-07
Time : 10:38:01

Exercises

  1. Display date in DD/MM/YYYY format