6
votes

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'   
1

1 Answers

7
votes

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