I have a method which takes a DateTime (currently as a string) which i then convert to a DateTime object, for example:
def foo(time)
the_time = Time.parse(time)
...
end
and so,
foo("2012-09-03")
I would like to also be able to parse a DateTime object:
foo(Time.now)
But Time.parse complains that I am not giving it a string:
NoMethodError: undefined method `gsub!' for 2012-08-08 15:59:00 UTC:Time
Is there an elegant (one line?) way to return a DateTime object from a string or DateTime object (i would prefer to avoid using if statements)
Thanks
Edit: Thanks for the comments – I have no real aversion to using an if statement, I was just seeing if there was anything nicer
Here’s one way to do it without
ifstatements:However if you’re looking for an elegant solution, I’d doubt that re-parsing date can be considered as such. Why do you think
ifis a bad option? Here’s how I’d do it: