now(...) public

Synonym for Time.new. Returns a Time object initialized tot he current system time.

Returns a Time object initialized to the current system time. Note: The object created will be created using the resolution available on your system clock, and so may include fractional seconds.

a = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
b = Time.new      #=> Wed Apr 09 08:56:03 CDT 2003
a == b            #=> false
"%.6f" % a.to_f   #=> "1049896563.230740"
"%.6f" % b.to_f   #=> "1049896563.231466"
Register or log in to add new notes.
August 17, 2009
1 thank

Freezing Time.now with Time.is

Sometimes when writing unit tests/specifications our code sets an attribute of an object using Time.now because running specs/test takes time.

The solution is to “freeze” Time.now with the following Time.is method:

class Time

  def self.metaclass
    class << self; self; end
  end

 # useful for unit testing
 # Time.is(Time.now) do
 #   Time.now # => Tue Nov 13 19:31:46 -0500 2007
 #   sleep 2
 #   Time.now # => Tue Nov 13 19:31:46 -0500 2007
 # end
 #
 # Time.is("10/05/2006") do
 #   Time.now # => Thu Oct 05 00:00:00 -0400 2006
 #   sleep 2
 #   Time.now # => Thu Oct 05 00:00:00 -0400 2006
 # end
  def self.is(point_in_time)
    new_time = case point_in_time
               when String then Time.parse(point_in_time)
               when Time then point_in_time
               else raise ArgumentError.new("argument should be a string or time instance")
               end
    class << self
      alias old_now now
    end
    metaclass.class_eval do
      define_method :now do
        new_time
      end
    end
    yield
    class << self
      alias now old_now
      undef old_now
    end
  end

end

It’s a good idea to add this to your spec_helper/test_helper and “freeze” time whenever you’re testing functionality that depends on a specific time value.

March 24, 2010
0 thanks

Time.now in UTC

A quick way to get the current time in UTC is:

Time.new.utc # => Wed Mar 24 14:38:19 UTC 2010
February 20, 2013
0 thanks

Freezing Time.now

You’d be much better off using the Timecop gem ( rubygems.org/gems/timecop ) than than manually writing monkey-patches to freeze Time.now etc.

It also supports time travel (i.e. changing the time, but allowing the clock to continue running).