When dealing with Time objects in Ruby, I run into a boundary problem. If you do it normally, it will not be a problem using the Range object, but I stumbled on it in an unusual way.
Ruby: 2.6.2 Rails: 5.1.2
Time.now.end_of_day
=> 2020-05-15 23:59:59 +0900
I want to take the next value of this.
This was the first thing I came up with
Time.now.end_of_day + 1
=> 2020-05-16 00:00:00 +0900
However, this is a mistake
(Time.now.end_of_day + 1).iso8601(3)
=> "2020-05-16T00:00:00.999+09:00"
+ 1
is an addition of 1 second until you get tired of it, and it does not move to the next value, so it cannot be used.
When I was fishing the Time class, I found a method that looked like that. https://docs.ruby-lang.org/ja/latest/method/Time/i/succ.html
Time.now.end_of_day.succ
(pry):109: warning: Time#succ is obsolete; use time + 1
=> 2020-05-16 00:00:00 +0900
However, it seems that he is just doing the same thing as + 1
because he is angry when he uses it because it is outdated. No good.
After all, I didn't know how to do it, so I pushed it
In the example problem, I only see a small number of 9 digits
(Time.now.end_of_day + 1).iso8601(10)
=> "2020-05-16T00:00:00.9999999990+09:00"
In other words, add 1 nanosecond.
(Time.now.end_of_day + 1/1000000000.0).iso8601(9)
=> "2020-05-16T00:00:00.000000000+09:00"
did it!
Time.now.iso8601(10)
=> "2020-05-15T19:56:55.4979370000+09:00"
Time.new(2020, 5, 16, 16, 59, 59.3).iso8601(9)
=> "2020-05-16T16:59:59.299999999+09:00"
Time.parse("2020-05-16T16:59:59.3+09:00").iso8601(9)
=> "2020-05-16T16:59:59.300000000+09:00"
Time.parse("2020-05-16T16:59:59.35555555555555555555+09:00").iso8601(20)
=> "2020-05-16T16:59:59.35555555555555555555+09:00"
Was no good
--You can have an infinite number of fractional seconds in a Time object --Therefore, there is no concept of the next value in the first place. ――However, it depends on how the Time object is created, so if you pull it from the DB, you can force it if you consider the number of valid digits. --In the first place, you should compare using the Range object obediently
Recommended Posts