Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

time
string
ruby
canonical
communitycreator

How to get the canonical string representation of a time in Ruby

okwudili onyejiaku

Overview

The goal of the ctime method is to get the canonical string representation of time. We can call it on any time object to return the canonical string representation of it.

Syntax

t.ctime

Parameters

t: This is the time object for which we want to get the canonical string representation.

Return value

The canonical string representation of any time object that calls the ctime method is returned.

Code example

# create time objects
t1 = Time.now
t2 = Time.new(2020)
t3 = Time.new(1999, 12)
t4 = Time.new(2001, 4, 18)

# get canonical
# string representation
a = t1.ctime
b = t2.ctime
c = t3.ctime
d = t4.ctime

puts a
puts b
puts c
puts d
Get canonical string representation of a time object in Ruby

Explanation

  • Lines 2-5: we create new time objects using Time.now and Time.new().

  • Lines 9-12: We call the ctime on the time objects we created to get their canonical string representations.

  • Lines 14-17: We print the strings.

RELATED TAGS

time
string
ruby
canonical
communitycreator
RELATED COURSES

View all Courses

Keep Exploring