Permalink
Browse files

Use `DateTime.parse` inside `String#to_datetime`

Use the standard library's `DateTime.parse` because it's marginally
faster and supports partial date/time strings.

Benchmark:
       user     system      total        real
old  3.980000   0.000000   3.980000 (  3.987606)
new  3.640000   0.010000   3.650000 (  3.641342)
  • Loading branch information...
1 parent b79adc4 commit ee3458217b4332c832be4fc47c091be8f2029064 @pixeltrix pixeltrix committed Jan 21, 2013
@@ -52,13 +52,6 @@ def to_date
# "2012-12-13 12:50".to_datetime #=> Thu, 13 Dec 2012 12:50:00 +0000
# "12/13/2012".to_datetime #=> ArgumentError: invalid date
def to_datetime
- unless blank?
- date_values = ::Date._parse(self, false).
- values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :sec_fraction).
- map! { |arg| arg || 0 }
- date_values[5] += date_values.pop
-
- ::DateTime.civil(*date_values)
- end
+ ::DateTime.parse(self, false) unless blank?
end
end
@@ -327,6 +327,12 @@ def test_string_to_datetime
assert_nil "".to_datetime
end
+ def test_partial_string_to_datetime
+ now = DateTime.now
+ assert_equal DateTime.civil(now.year, now.month, now.day, 23, 50), "23:50".to_datetime
+ assert_equal DateTime.civil(now.year, now.month, now.day, 23, 50, 0, "-04:00"), "23:50 -0400".to_datetime
+ end
+
def test_string_to_date
assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date
assert_nil "".to_date

0 comments on commit ee34582

Please sign in to comment.