samarth
samarth

Reputation: 89

Change date format in rails 4

I have got date format in my text_field like this -> 2014-11-14 20:45:00

I want to enter in my database in rails 4. how can i save it very easy way in my database column type "datetime"?.

I have tried below way but it seems no working.

params[:task_assign][:task_assign_scheduled_on]=DateTime.civil(
params[:task_assign][:"task_assign_scheduled_on(1i)"].to_i,
params[:task_assign][:"task_assign_scheduled_on(2i)"].to_i,
params[:task_assign][:"task_assign_scheduled_on(3i)"].to_i,
params[:task_assign][:"task_assign_scheduled_on(4i)"].to_i,
params[:task_assign][:"task_assign_scheduled_on(5i)"].to_i)

Upvotes: 0

Views: 269

Answers (2)

Ahmad Elassuty
Ahmad Elassuty

Reputation: 4744

In posgres database actually your format will be saved without any further casting but you can just try to use to_datetime if helps

ex

"2014-11-14 20:45:00".to_datetime

--> Fri, 14 Nov 2014 20:45:00 +0000

But also this is not the format that will be save to your database so that i told you nothing wrong with your format to be saved directly.

If you tried to get a datetime column form your database it will look like this:

Fri, 14 Nov 2014 14:44:03 UTC +00:00

I do not know if that differs from one database to the other or there is something worng with activerecord which handles it automatically.

Upvotes: 1

tagCincy
tagCincy

Reputation: 1599

ActiveRecord automagically converts a valid DateTime string upon persisting the record. The format that gets saved to the DB is dependent on the DB you are using and it settings. Typically, PG will save any DateTime as a UTC DateTime string.

If you want to save a DateTime in a particular format, you need to either update your DB settings, or just save the attribute as a string.

Upvotes: 1

Related Questions