提交 726b5d79 编写于 作者: D Daniel Neighman 提交者: wycats

updates String#to_(date|date_time|time) to return nil for blank strings

上级 b73177a0
......@@ -30,16 +30,19 @@ def ord
# Form can be either :utc (default) or :local.
def to_time(form = :utc)
return nil if self.blank?
d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction).map { |arg| arg || 0 }
d[6] *= 1000000
::Time.send("#{form}_time", *d)
end
def to_date
return nil if self.blank?
::Date.new(*::Date._parse(self, false).values_at(:year, :mon, :mday))
end
def to_datetime
return nil if self.blank?
d = ::Date._parse(self, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :sec_fraction).map { |arg| arg || 0 }
d[5] += d.pop
::DateTime.civil(*d)
......
......@@ -117,17 +117,20 @@ def test_string_to_time
assert_equal Time.local(2005, 2, 27, 23, 50, 19, 275038), "2005-02-27T23:50:19.275038".to_time(:local)
assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time
assert_equal Time.local_time(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_time(:local)
assert_equal nil, "".to_time
end
def test_string_to_datetime
assert_equal DateTime.civil(2039, 2, 27, 23, 50), "2039-02-27 23:50".to_datetime
assert_equal 0, "2039-02-27 23:50".to_datetime.offset # use UTC offset
assert_equal ::Date::ITALY, "2039-02-27 23:50".to_datetime.start # use Ruby's default start value
assert_equal DateTime.civil(2039, 2, 27, 23, 50, 19 + Rational(275038, 1000000), "-04:00"), "2039-02-27T23:50:19.275038-04:00".to_datetime
assert_equal nil, "".to_datetime
end
def test_string_to_date
assert_equal Date.new(2005, 2, 27), "2005-02-27".to_date
assert_equal nil, "".to_date
end
def test_access
......@@ -255,7 +258,7 @@ def test_mb_chars_returns_string
string.rb - Interpolation for String.
Copyright (C) 2005-2009 Masao Mutoh
You may redistribute it and/or modify it under the same
license terms as Ruby.
=end
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册