[Feature request] beginning_of_second and end_of_second

For consistency with beginning_of_minute and end_of_minute (and _hour etc.) I suggest adding beginning_of_second and end_of_second.

This is useful when e.g. when dealing with database columns without sub-second precision.

2 Likes

I honestly do not see any sense to add end_of_second :slight_smile:

Unless it’s a joke :slight_smile:

Is end_of_second well defined? All the Rubies I have access report DateTime as having nanosecond precision, but the other end_of_ methods assume microseconds.

def end_of_second
  change(usec: Rational(999999999, 1000)
end

I’m not sure what you mean by columns without sub-second precision and how you think this would interact with your code.

Not a joke :slight_smile:

In many databases, a DATETIME column does not support microseconds. Trying to store a DateTime will simply truncate the microsecond part.

end_of_minute is defined as XX:XX:59.999999. Likewise for the other end_of_ methods. I suggest following this definition for end_of_second as well.

Use-cases

Example 1

If the users.last_login_at column does not have sub-second precision, the where query will not return the row just updated without beginning_of_second.

time = Time.now
user.update last_login_at: time
User.where('last_login_at >= ?', time.beginning_of_second)

I don’t know when you would make such a query in practice, but you often do similar stuff when writing tests. E.g. the following will fail.

assert_equal time, user.reload.last_login_at

Example 2

If you do not use beginning_of_second, you will not be able to use the database query cache for this query.

Article.where('published_at >= ?', Time.now.beginning_of_second)

Ready for PR, if people support this proposal:

https://github.com/c960657/rails/commit/f7c8f44b91109f3b4b3efa7ea7b8b6e2a8b99970

2 Likes