On this page
- Epoch Seconds
- Time Resolution
- Examples
- Creating a New Time Instance
- Working with an Instance of Time
- What’s Here
- Methods for Creating
- Methods for Fetching
- Methods for Querying
- Methods for Comparing
- Methods for Converting
- Methods for Rounding
- Timezone Specifiers
- Hours/Minutes Offsets
- Single-Letter Offsets
- Integer Offsets
- Timezone Objects
- Timezone Names
- Class methods
- Instance methods
- Constants
- Ruby version changes
Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →
Time
A Time object represents a date and time:
Time.new(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 -0600
Although its value can be expressed as a single numeric (see Epoch Seconds below), it can be convenient to deal with the value by parts:
t = Time.new(-2000, 1, 1, 0, 0, 0.0) # => -2000-01-01 00:00:00 -0600 t.year # => -2000 t.month # => 1 t.mday # => 1 t.hour # => 0 t.min # => 0 t.sec # => 0 t.subsec # => 0 t = Time.new(2000, 12, 31, 23, 59, 59.5) # => 2000-12-31 23:59:59.5 -0600 t.year # => 2000 t.month # => 12 t.mday # => 31 t.hour # => 23 t.min # => 59 t.sec # => 59 t.subsec # => (1/2)
Epoch Seconds
Epoch seconds is the exact number of seconds (including fractional subseconds) since the Unix Epoch, January 1, 1970.
You can retrieve that value exactly using method Time.to_r:
Time.at(0).to_r # => (0/1) Time.at(0.999999).to_r # => (9007190247541737/9007199254740992)
Other retrieval methods such as Time#to_i and Time#to_f may return a value that rounds or truncates subseconds.
Time Resolution
A Time object derived from the system clock (for example, by method Time.now) has the resolution supported by the system.
Examples
All of these examples were done using the EST timezone which is GMT-5.
Creating a New Time Instance
You can create a new instance of Time with Time.new. This will use the current system time. Time.now is an alias for this. You can also pass parts of the time to Time.new such as year, month, minute, etc. When you want to construct a time this way you must pass at least a year. If you pass the year with nothing else time will default to January 1 of that year at 00:00:00 with the current system timezone. Here are some examples:
Time.new(2002) #=> 2002-01-01 00:00:00 -0500 Time.new(2002, 10) #=> 2002-10-01 00:00:00 -0500 Time.new(2002, 10, 31) #=> 2002-10-31 00:00:00 -0500
You can pass a UTC offset:
Time.new(2002, 10, 31, 2, 2, 2, "+02:00") #=> 2002-10-31 02:02:02 +0200
zone = timezone("Europe/Athens") # Eastern European Time, UTC+2 Time.new(2002, 10, 31, 2, 2, 2, zone) #=> 2002-10-31 02:02:02 +0200
You can also use Time.local and Time.utc to infer local and UTC timezones instead of using the current system setting.
You can also create a new time using Time.at which takes the number of seconds (with subsecond) since the Unix Epoch.
Time.at(628232400) #=> 1989-11-28 00:00:00 -0500
Working with an Instance of Time
Once you have an instance of Time there is a multitude of things you can do with it. Below are some examples. For all of the following examples, we will work on the assumption that you have done the following:
t = Time.new(1993, 02, 24, 12, 0, 0, "+09:00")
Was that a monday?
t.monday? #=> false
What year was that again?
t.year #=> 1993
Was it daylight savings at the time?
t.dst? #=> false
What’s the day a year later?
t + (60*60*24*365) #=> 1994-02-24 12:00:00 +0900
How many seconds was that since the Unix Epoch?
t.to_i #=> 730522800
You can also do standard functions like compare two times.
t1 = Time.new(2010) t2 = Time.new(2011) t1 == t2 #=> false t1 == t1 #=> true t1 < t2 #=> true t1 > t2 #=> false Time.new(2010,10,31).between?(t1, t2) #=> true
What’s Here
First, what’s elsewhere. Class Time:
-
Inherits from class Object.
-
Includes module Comparable.
Here, class Time provides methods that are useful for:
Methods for Creating
-
::new: Returns a new time from specified arguments (year, month, etc.), including an optional timezone value. -
::local(aliased as::mktime): Same as::new, except the timezone is the local timezone. -
::utc(aliased as::gm): Same as::new, except the timezone is UTC. -
::at: Returns a new time based on seconds since epoch. -
::now: Returns a new time based on the current system time. -
+(plus): Returns a new time increased by the given number of seconds. -
-(minus): Returns a new time decreased by the given number of seconds.
Methods for Fetching
-
year: Returns the year of the time. -
hour: Returns the hours value for the time. -
min: Returns the minutes value for the time. -
sec: Returns the seconds value for the time. -
usec(aliased astv_usec): Returns the number of microseconds in the subseconds value of the time. -
nsec(aliased astv_nsec: Returns the number of nanoseconds in the subsecond part of the time. -
subsec: Returns the subseconds value for the time. -
wday: Returns the integer weekday value of the time (0 == Sunday). -
yday: Returns the integer yearday value of the time (1 == January 1). -
hash: Returns the integer hash value for the time. -
utc_offset(aliased asgmt_offsetandgmtoff): Returns the offset in seconds between time and UTC. -
to_f: Returns the float number of seconds since epoch for the time. -
to_i(aliased astv_sec): Returns the integer number of seconds since epoch for the time. -
to_r: Returns theRationalnumber of seconds since epoch for the time. -
zone: Returns a string representation of the timezone of the time.
Methods for Querying
-
dst?(aliased asisdst): Returns whether the time is DST (daylight saving time). -
sunday?: Returns whether the time is a Sunday. -
monday?: Returns whether the time is a Monday. -
tuesday?: Returns whether the time is a Tuesday. -
wednesday?: Returns whether the time is a Wednesday. -
thursday?: Returns whether the time is a Thursday. -
friday?: Returns whether time is a Friday. -
saturday?: Returns whether the time is a Saturday.
Methods for Comparing
Methods for Converting
-
inspect: Returns the time in detail as a string. -
strftime: Returns the time as a string, according to a given format. -
to_a: Returns a 10-element array of values from the time. -
to_s: Returns a string representation of the time. -
getutc(aliased asgetgm): Returns a new time converted to UTC. -
getlocal: Returns a new time converted to local time. -
localtime: Converts time to local time in place. -
deconstruct_keys: Returns a hash of time components used in pattern-matching.
Methods for Rounding
-
round:Returns a new time with subseconds rounded. -
ceil: Returns a new time with subseconds raised to a ceiling. -
floor: Returns a new time with subseconds lowered to a floor.
For the forms of argument zone, see Timezone Specifiers.
Timezone Specifiers
Certain Time methods accept arguments that specify timezones:
-
Time.at: keyword argumentin:. -
Time.new: positional argumentzoneor keyword argumentin:. -
Time.now: keyword argumentin:. -
Time#getlocal: positional argumentzone. -
Time#localtime: positional argumentzone.
The value given with any of these must be one of the following (each detailed below):
Hours/Minutes Offsets
The zone value may be a string offset from UTC in the form '+HH:MM' or '-HH:MM', where:
-
HHis the 2-digit hour in the range0..23. -
MMis the 2-digit minute in the range0..59.
Examples:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: '-23:59') # => 1999-12-31 20:16:01 -2359 Time.at(t, in: '+23:59') # => 2000-01-02 20:14:01 +2359
Single-Letter Offsets
The zone value may be a letter in the range 'A'..'I' or 'K'..'Z'; see List of military time zones:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: 'A') # => 2000-01-01 21:15:01 +0100 Time.at(t, in: 'I') # => 2000-01-02 05:15:01 +0900 Time.at(t, in: 'K') # => 2000-01-02 06:15:01 +1000 Time.at(t, in: 'Y') # => 2000-01-01 08:15:01 -1200 Time.at(t, in: 'Z') # => 2000-01-01 20:15:01 UTC
Integer Offsets
The zone value may be an integer number of seconds in the range -86399..86399:
t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC Time.at(t, in: -86399) # => 1999-12-31 20:15:02 -235959 Time.at(t, in: 86399) # => 2000-01-02 20:15:00 +235959
Timezone Objects
The zone value may be an object responding to certain timezone methods, an instance of Timezone and TZInfo for example.
The timezone methods are:
-
local_to_utc:-
Called when
Time.newis invoked withtzas the value of positional argumentzoneor keyword argumentin:. -
Argument: a Time-like object.
-
Returns: a Time-like object in the UTC timezone.
-
-
utc_to_local:-
Called when
Time.atorTime.nowis invoked withtzas the value for keyword argumentin:, and whenTime#getlocalorTime#localtimeis called withtzas the value for positional argumentzone. -
Argument: a Time-like object.
-
Returns: a Time-like object in the local timezone.
-
A custom timezone class may have these instance methods, which will be called if defined:
-
abbr:-
Called when
Time#strftimeis invoked with a format involving%Z. -
Argument: a Time-like object.
-
Returns: a string abbreviation for the timezone name.
-
-
dst?:-
Called when
Time.atorTime.nowis invoked withtzas the value for keyword argumentin:, and whenTime#getlocalorTime#localtimeis called withtzas the value for positional argumentzone. -
Argument: a Time-like object.
-
Returns: whether the time is daylight saving time.
-
-
name:-
Called when
Marshal.dump(t)is invoked -
Argument: none.
-
Returns: the string name of the timezone.
-
Time-Like Objects
A Time-like object is a container object capable of interfacing with timezone libraries for timezone conversion.
The argument to the timezone conversion methods above will have attributes similar to Time, except that timezone related attributes are meaningless.
The objects returned by local_to_utc and utc_to_local methods of the timezone object may be of the same class as their arguments, of arbitrary object classes, or of class Integer.
For a returned class other than Integer, the class must have the following methods:
-
year -
mon -
mday -
hour -
min -
sec -
isdst
For a returned Integer, its components, decomposed in UTC, are interpreted as times in the specified timezone.
Timezone Names
If the class (the receiver of class methods, or the class of the receiver of instance methods) has find_timezone singleton method, this method is called to achieve the corresponding timezone object from a timezone name.
For example, using Timezone:
class TimeWithTimezone < Time require 'timezone' def self.find_timezone(z) = Timezone[z] end TimeWithTimezone.now(in: "America/New_York") #=> 2023-12-25 00:00:00 -0500 TimeWithTimezone.new("2023-12-25 America/New_York") #=> 2023-12-25 00:00:00 -0500
Or, using TZInfo:
class TimeWithTZInfo < Time require 'tzinfo' def self.find_timezone(z) = TZInfo::Timezone.get(z) end TimeWithTZInfo.now(in: "America/New_York") #=> 2023-12-25 00:00:00 -0500 TimeWithTZInfo.new("2023-12-25 America/New_York") #=> 2023-12-25 00:00:00 -0500
You can define this method per subclasses, or on the toplevel Time class.
Class methods 16
Instance methods 65
A hash of timezones mapped to hour differences from UTC. The set of time zones corresponds to the ones specified by RFC 2822 and ISO 8601.
Ruby version changes 5
-
3.3
-
Time.newwith a string argument became stricter. [Bug #19293]ExampleTime.new('2023-12-20') # no time information (ArgumentError)
-
-
3.2
-
Time#deconstruct_keysis added, allowing to useTimeinstances in pattern-matching expressions [Feature #19071] -
Time.newnow can parse a string like generated byTime#inspectand return aTimeinstance based on the given argument. [Feature #18033]
-
-
3.1
-
Time.newnow accepts optionalin:keyword argument for the timezone, as well asTime.atandTime.now, so that is now you can omit minor arguments toTime.new. [Feature #17485]ExampleTime.new(2021, 12, 25, in: "+07:00") #=> 2021-12-25 00:00:00 +0700
At the same time, time component strings are converted to integers more strictly now.
ExampleTime.new(2021, 12, 25, "+07:30") #=> invalid value for Integer(): "+07:30" (ArgumentError)
Ruby 3.0 or earlier returned probably unexpected result
2021-12-25 07:00:00, not2021-12-25 07:30:00nor2021-12-25 00:00:00 +07:30. -
Time#strftimesupports RFC 3339 UTC for unknown offset local time,-0000, as%-z. [Feature #17544]
-