Time and date

Contents
Time.now
Format with strftime
Parse input
Date arithmetic

Time.now

Time dot now captures the current moment with date and clock time together. Print it during logging to see exactly when events happen.

Time objects compare with plain operators, so finding the later of two moments needs no extra library. Dates often arrive as text, so the string skills from Encodings pair well with this lesson.

now = Time.now puts now

Format with strftime

strftime turns a Time into text using percent codes for year, month, day, hours, and minutes. You arrange the codes with any separators you like.

One format string can serve logs, file names, and screen output without extra helpers.

t = Time.now puts t.strftime("%Y-%m-%d")

Parse input

The time library adds parsing of common formats. Require it first, then pass the user text to parse.

Invalid text raises an error, so validate around parsing when input comes from strangers.

require "time" t = Time.parse("2026-10-06") puts t.year

Date arithmetic

The date library adds calendar math without clock time. today gives the current date, and plus or minus a number shifts by days.

Subtracting two dates gives the gap between them, which to_i turns into whole days.

require "date" today = Date.today puts today + 7

Next: JSON and YAML

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.ru
Write to info@urn.su, info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: