Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

class method

Time.new

new(year = (now = true), mon = nil, mday = nil, hour = nil, min = nil, sec = nil, zone = nil, in: nil)

Returns a new Time object based on the given arguments.

With no positional arguments, returns the value of Time.now:

Example
Time.new                                       # => 2021-04-24 17:27:46.0512465 -0500

Otherwise, returns a new Time object based on the given parameters:

Example
Time.new(2000)                                 # => 2000-01-01 00:00:00 -0600
Time.new(2000, 12, 31, 23, 59, 59.5)           # => 2000-12-31 23:59:59.5 -0600
Time.new(2000, 12, 31, 23, 59, 59.5, '+09:00') # => 2000-12-31 23:59:59.5 +0900

Parameters:

  • year: an integer year.

  • month: a month value, which may be:

    • An integer month in the range 1..12.

    • A 3-character string that matches regular expression /jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/i.

  • day: an integer day in the range 1..31 (less than 31 for some months).

  • hour: an integer hour in the range 0..23.

  • min: an integer minute in the range 0..59.

  • sec is the number of seconds (Integer, Float, or Rational) in the range 0..60.

  • zone: a timezone, which may be:

    • A string offset from UTC.

    • A single letter offset from UTC, in the range 'A'..'Z', 'J' (the so-called military timezone) excluded.

    • An integer number of seconds.

    • A timezone object; see Timezone Argument for details.

  • in: zone: a timezone zone, which may be as above.

Ruby version changes

  1. 3.1
    • Time.new now accepts optional in: keyword argument for the timezone, as well as Time.at and Time.now, so that is now you can omit minor arguments to Time.new. [Feature #17485]

      Example
      Time.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.

      Example
      Time.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, not 2021-12-25 07:30:00 nor 2021-12-25 00:00:00 +07:30.

See also .local .now .json_create .parse also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0