Is there a way to add 1 millisecond to a Time/DateTime object in Ruby?
For an Webservice Request i need a time scoping with milliseconds:
irb(main):034:0> time_start = Date.today.to_time.utc.iso8601(3)
=> "2016-09-27T22:00:00.000Z"
irb(main):035:0> time_end = ((Date.today + 1).to_time).utc.iso8601(3)
=> "2016-09-28T22:00:00.000Z"
-- or --
irb(main):036:0> time_end = ((Date.today + 1).to_time - 1).utc.iso8601(3)
=> "2016-09-28T21:59:59.000Z"
So I'm near my prefered solution, but time_end should be 2016-09-28T21:59:59.999Z
.
I didn't find solutions that Ruby can handle calculating with milliseconds. I only did it with strftime, but it would be great if there is a possibility to calculate.
-- This works, but hard coded --
time_end = ((Date.today + 1).to_time - 1).utc.strftime("%Y-%m-%dT%H:%M:%S.999Z")
=> "2016-09-28T21:59:59.999Z"
FYI: I'm on plain Ruby, no Rails.
Ok i found a solution. With real calculation i looks like.
time_end = ((Date.today + 1).to_time - 1/1001).utc.iso8601(3)
=> "2016-09-28T21:59:59.999Z"
EXAMPLE
Formatting in iso8601(3) is only to show behavior.
irb(main):055:0> Date.today.to_time.iso8601(3)
=> "2016-09-28T00:00:00.000+02:00
Adding a millisecond"
irb(main):058:0> (Date.today.to_time + 1/1000.0).iso8601(3)
=> "2016-09-28T00:00:00.001+02:00"
Subtract a millisecond
!DONT USE, see result with subtracted 2 milliseconds!
irb(main):060:0> (Date.today.to_time - 1/1000.0).iso8601(3)
=> "2016-09-27T23:59:59.998+02:00"
USE
irb(main):061:0> (Date.today.to_time - 1/1001.0).iso8601(3)
=> "2016-09-27T23:59:59.999+02:00"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With