Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 Compare DateTimes Without Milliseconds

I am trying to compare datetimes accurately in a Rails 4 API serving JSON. When sending dates in rfc3339 format to the API like this

"2015-05-06T21:16:43.611-0400"

the comparisons don't work properly because Rails 4 compares datetimes with microsecond precision whereas dates are sent with milliseconds precision

Is there a way to "limit" the comparison to milliseconds when doing something like

object.created_at > '2015-05-06T21:16:43.611-0400'   
like image 737
stefano_cdn Avatar asked May 07 '15 17:05

stefano_cdn


1 Answers

You can strip out the milliseconds by doing object.created_at.change(sec: object.created_at.sec) This returns a new datetime object with everything under the seconds zeroed out, it won't change the datetime in your DB.

I wish there was a nicer way to do it but DateTime#change in Rails 4 does not support usec, despite the internet being full of people saying to use it.

You could write a helper to make this tidier,

def strip_milliseconds(datetime)
    datetime.change sec: datetime.created_at.sec
end
like image 150
Mario Avatar answered Oct 17 '22 03:10

Mario