Skip to content

Commit

Permalink
Ruby 1.8.7+ provides to_date/to_datetime, AS just makes them public.
Browse files Browse the repository at this point in the history
  • Loading branch information
John Firebaugh committed Jan 6, 2011
1 parent 25eec09 commit 9f05d07
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 35 deletions.
22 changes: 0 additions & 22 deletions activesupport/lib/active_support/core_ext/time/conversions.rb
Expand Up @@ -55,31 +55,9 @@ def formatted_offset(colon = true, alternate_utc_string = nil)
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
end

# Converts a Time object to a Date, dropping hour, minute, and second precision.
#
# my_time = Time.now # => Mon Nov 12 22:59:51 -0500 2007
# my_time.to_date # => Mon, 12 Nov 2007
#
# your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
# your_time.to_date # => Tue, 13 Jan 2009
def to_date
::Date.new(year, month, day)
end unless method_defined?(:to_date)

# A method to keep Time, Date and DateTime instances interchangeable on conversions.
# In this case, it simply returns +self+.
def to_time
self
end unless method_defined?(:to_time)

# Converts a Time instance to a Ruby DateTime instance, preserving UTC offset.
#
# my_time = Time.now # => Mon Nov 12 23:04:21 -0500 2007
# my_time.to_datetime # => Mon, 12 Nov 2007 23:04:21 -0500
#
# your_time = Time.parse("1/13/2009 1:13:03 P.M.") # => Tue Jan 13 13:13:03 -0500 2009
# your_time.to_datetime # => Tue, 13 Jan 2009 13:13:03 -0500
def to_datetime
::DateTime.civil(year, month, day, hour, min, sec, Rational(utc_offset, 86400))
end unless method_defined?(:to_datetime)
end
16 changes: 3 additions & 13 deletions activesupport/test/core_ext/time_ext_test.rb
Expand Up @@ -533,19 +533,9 @@ def test_custom_date_format
Time::DATE_FORMATS.delete(:custom)
end

def test_to_date
assert_equal Date.new(2005, 2, 21), Time.local(2005, 2, 21, 17, 44, 30).to_date
end

def test_to_datetime
assert_equal Time.utc(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, 0, 0)
with_env_tz 'US/Eastern' do
assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0)
end
with_env_tz 'NZ' do
assert_equal Time.local(2005, 2, 21, 17, 44, 30).to_datetime, DateTime.civil(2005, 2, 21, 17, 44, 30, Rational(Time.local(2005, 2, 21, 17, 44, 30).utc_offset, 86400), 0)
end
assert_equal ::Date::ITALY, Time.utc(2005, 2, 21, 17, 44, 30).to_datetime.start # use Ruby's default start value
def test_conversion_methods_are_publicized
assert Time.public_instance_methods.include?(:to_date) || Time.public_instance_methods.include?('to_date')
assert Time.public_instance_methods.include?(:to_datetime) || Time.public_instance_methods.include?('to_datetime')
end

def test_to_time
Expand Down

0 comments on commit 9f05d07

Please sign in to comment.