Ruby Time.parse incorrectly returns timestamp for String

Viewed 87

I am facing a weird bug (?) in Ruby

Time.parse("David").to_i returns "no time information in "David"`

Time.parse("David1").to_i returns "no time information in "David1"`

However

Time.parse("David10").to_i returns 1570654800

It seems that any string with more than 2 numbers at the end manages to pass the Time conversion in Ruby. Is this a bug?

I am trying to create a single method than can handle conversion of strings to Timestamps where relevant or simply back to strings if conversion is not possible but for instances where my string includes 2+ numbers, it fails

if value.is_a? String
  # if it's string of a date format
  begin
    Time.parse(value).to_i
  rescue StandardError => e
    value.downcase
  end
  # it's another object type - probably DateTime, Time or Date
else
  value.nil? ? 0 : value.to_f
end
1 Answers

Internally time.rb uses, following,

def parse(date, now=self.now)
  comp = !block_given?
  d = Date._parse(date, comp)
  year = d[:year]
  year = yield(year) if year && !comp
  make_time(date, year, d[:mon], d[:mday], d[:hour], d[:min], d[:sec], d[:sec_fraction], d[:zone], now)
end

It used to parse day, month later year by precision, Range of digits when exeed to 3, it consider it as year

Related