Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails convert date format

I have a form input in my application that accepts dates in the format DD/MM/YYYY eg 02/05/2012 is 2nd May 2012.

What is the best way for me to convert this into a suitable format to be added to the database through ActiveRecord?

Is there a simply way of converting 02/05/2012 to 05/02/2012 before adding to the database?

like image 998
Jack Avatar asked Jun 27 '12 12:06

Jack


2 Answers

This is similar to Getting rails to accept European date format (dd/mm/yyyy)

In your model, create a setter method, where "my_date" is your database field.

def my_date=(val)
  Date.strptime(val, "%d/%m/%Y") if val.present?
end
like image 110
Jeremy Peterson Avatar answered Oct 24 '22 19:10

Jeremy Peterson


For this specific format you can call DateTime.parse:

DateTime.parse("02/05/2012") # => Thu, 02 May 2012 00:00:00 +0000
like image 40
Stefan Avatar answered Oct 24 '22 19:10

Stefan