Hi,
I'm looking for the best way to take a datetime string from MySQL, explode it in Ruby and return the month, date, and year in separate elements.
Hi,
I'm looking for the best way to take a datetime string from MySQL, explode it in Ruby and return the month, date, and year in separate elements.
How is the string formatted? You could just convert the datetime string into a datetime object, and call the instance methods.
require 'time'
x = "2009/04/16 19:52:30" #grab your datetime string from the database and assign it
y = DateTime.strptime(x, "%Y/%m/%d %H:%M:%S") #create a new date object
Then a simple y.day() yields:
y.day() = 16
and y.hour():
y.hour() = 19
FYI never actually used Ruby much, so this is what I got out of playing with the console, so hopefully this helps shed some light.
require 'time'
x = "2009/04/16 19:52:30"
begin
y = Time.parse(x)
[y.year, y.month, y.day] # => [2009, 4, 16]
rescue ArgumentError
puts "cannot parse date: #{x}"
end