Skip to main content

How to Get the Current Unix Time in Ruby

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Unix time counts the seconds since 1 January 1970 UTC, and many formats store times that way. In Ruby, Time.now.to_i gives the current Unix time as a whole number, and Time.at turns such a number back into a Time.

Syntax​

Syntax
<seconds> = Time.now.to_i
<time> = Time.at(<seconds>).utc
PartWhat it does
Time.nowThe current time.
.to_iIts Unix time in whole seconds; fractions are dropped.
Time.at(<seconds>)A Time for those seconds.
.utcShows that time in UTC.

The Ruby documentation for Time#to_i: "Returns the value of self as integer Epoch seconds; subseconds are truncated (not rounded)".

The Example​

The example prints the current Unix time, then the same moment as a UTC date and time.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, which stores Time.now.to_i in now, puts now, and puts Time.at(now).utc.

main.rb
now = Time.now.to_i

puts now
puts Time.at(now).utc

Step 2: Run It​

Terminal
ruby main.rb
Output
1795679779
2026-11-26 07:56:19 UTC

A zsh terminal where ruby main.rb prints 1795679779 and 2026-11-26 07:56:19 UTC.

Your numbers will differ. The command is the same in zsh, bash and PowerShell.

Times in the Future​

Unix time is a plain number of seconds, so adding time is arithmetic: Time.now.to_i + 15 * 60 is 15 minutes from now.

Common Mistakes​

MistakeWhat happensDo this instead
Printing Time.at(...) without .utcIt's shown in the computer's local time zoneAdd .utc
Using to_f where whole seconds are expectedYou get a decimal with the fraction of a secondUse to_i
Treating the number as millisecondsIt's seconds; JavaScript's Date.now() is millisecondsMultiply or divide by 1,000 when exchanging values

Troubleshooting​

SymptomLikely causeFix
A converted time is hours offIt was shown in local timeCall .utc
A date far in the futureMilliseconds were read as secondsDivide by 1,000

FAQ​

How do I get fractions of a second?​

Time.now.to_f returns the Unix time as a Float.

Does the time zone change the number?​

No. Unix time counts seconds since a fixed UTC moment; the zone only matters when you display it.

Conclusion​

Time.now.to_i returns the current Unix time in seconds, arithmetic moves it, and Time.at(seconds).utc turns it back into a readable UTC time.

Additional Resources​

  • Time, in the Ruby documentation.