Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How to change created_at time?

In my controller I have:

@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 item it the created_at column is:

2012-02-27 16:35:18

I would expect it to be:

2012-02-27 00:00:00
like image 661
Rails beginner Avatar asked Feb 27 '12 16:02

Rails beginner


2 Answers

Your problem is that strftime only formats the time, it doesn't actually change the time.

So when you do Time.now, that returns the time. Strftime only changes the way that its represented.

If you wanted to change the created_at date to "2012-02-27 00:00:00", just pass that in to @koncurrencer.created_at

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

That should do it.

In response to your question:

What you were doing should work just fine then. In fact you can just say:

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

and that should work just fine.

If you wanted to always have the time be at the beginning of the day you could use Date.today instead of Time.now since that always returns the time component of the Date as "00:00:00"

Here is what you want:

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

That should be more clear.

like image 184
TheDelChop Avatar answered Nov 10 '22 19:11

TheDelChop


If you want to set the time always to "00:00:00", you can go by this:

t = Time.now
=> 2012-02-27 17:46:38 +0100

t2 = Time.parse("00:00:00", t)
=> 2012-02-27 00:00:00 +0100
like image 1
Daniel Blaichinger Avatar answered Nov 10 '22 19:11

Daniel Blaichinger