Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i remove the milliseconds from date time in rails?

I have to compare the date in rails to get the values after that date I have send the date as "2013-03-04T06:26:25Z"but actually the record in the db contains date as follows 2013-03-04 06:26:25.817149 so when i check with the date it also returns that record but i want records after that date. how can i remove the milliseconds from the db? please help me.

like image 960
logesh Avatar asked Mar 04 '13 10:03

logesh


3 Answers

I had a similar problem

Update your time object like this before sending it to the database :

time.change(:usec => 0)
like image 126
Intrepidd Avatar answered Oct 05 '22 02:10

Intrepidd


Since ruby 1.9 you can use round

t = Time.now.round
t.usec # => 0
like image 43
Nathan Avatar answered Oct 05 '22 02:10

Nathan


I was also having this problem, however when I was applying the change as indicated in @Intrepidd's answer, it wasn't affecting the microseconds of my time object.

Please note that (at least currently) the :usec key only works with the Time#change method, and not with the DateTime#change method.

The DateTime#change method ignores the keys that it doesn't accept, so you wouldn't be able to tell that your attempted change of the microseconds didn't work unless you inspected the object further (such as with DateTime#rfc3339(9)).

So before you attempt this change, make sure that you are working with a Time object, not a DateTime object.

like image 42
pjrebsch Avatar answered Oct 05 '22 02:10

pjrebsch