Rails - How to change created_at time?

In my controller, I:

@konkurrencer = Rating.new(params[:kon]) @konkurrencer.save @konkurrencer.konkurrencer.rating_score += params[:kon][:ratings].to_i @konkurrencer.konkurrencer.ratings += 1 @konkurrencer.created_at = Time.now.strftime("%Y-%m-%d 00:00:00") @konkurrencer.save 

When I create a new element, the created_at column:

 2012-02-27 16:35:18 

I expect this to be:

 2012-02-27 00:00:00 
+4
source share
2 answers

Your problem is that strftime only formats the time; it does not actually change the time.

So, when you do Time.now, it returns the time. Strftime only changes the way it is presented.

If you want to change the created_at date to "2012-02-27 00:00:00" just go to @koncurrencer.created_at

 @koncurrencer.created_at = "2012-02-27 00:00:00" 

That should do it.

In answer to your question:

What you did should work perfectly. In fact, you can just say:

 @koncurrencer.created_at = Time.now @koncurrencer.save 

and this should work fine.

If you want to always have time at the beginning of the day, you can use Date.today instead of Time.now , since it always returns the Date time component as "00:00:00"

Here is what you want:

 @koncurrencer.created_at = Date.today @koncurrencer.save 

It should be more clear.

+16
source

If you want to set the time always to "00:00:00", you can go as follows:

 t = Time.now => 2012-02-27 17:46:38 +0100 t2 = Time.parse("00:00:00", t) => 2012-02-27 00:00:00 +0100 
+1
source

Source: https://habr.com/ru/post/1398642/


All Articles