Skip to content

Commit eaef958

Browse files
p-mongop
andauthored
Fix RUBY-2145 bson 4.8.0 rounds Time during serialization to bson/extended json (#190)
* Fix RUBY-2145 bson 4.8.0 rounds Time during serialization to bson/extended json * fix for older ruby versions * compatibility with ruby 2.3 * add jruby debugging tools * test times that precede unix epoch * work around jruby rounding times up Co-authored-by: Oleg Pudeyev <[email protected]>
1 parent 833b693 commit eaef958

File tree

1 file changed

+39
-5
lines changed

1 file changed

+39
-5
lines changed

docs/tutorials/bson-v4.txt

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -555,12 +555,46 @@ them.
555555
- ``{ "$regex" : "[abc]", "$options" : "i" }``
556556

557557

558-
Special Ruby Date Classes
559-
-------------------------
558+
Time Instances
559+
--------------
560560

561-
Ruby's ``Date`` and ``DateTime`` are able to be serialized, but when they are
562-
deserialized, they will always be returned as a ``Time`` since the BSON
563-
specification only has a ``Time`` type and knows nothing about Ruby.
561+
Times in Ruby can have nanosecond precision. Times in BSON (and MongoDB)
562+
can only have microsecond precision. When Ruby ``Time`` instances are
563+
serialized to BSON or Extended JSON, the times are floored to the nearest
564+
millisecond.
565+
566+
.. note::
567+
568+
The time as always rounded down. If the time precedes the Unix epoch
569+
(January 1, 1970 00:00:00 UTC), the absolute value of the time would
570+
increase:
571+
572+
.. code-block:: ruby
573+
574+
time = Time.utc(1960, 1, 1, 0, 0, 0, 999_999)
575+
time.to_f
576+
# => -315619199.000001
577+
time.floor(3).to_f
578+
# => -315619199.001
579+
580+
.. note::
581+
582+
JRuby as of version 9.2.11.0 `rounds pre-Unix epoch times up rather than
583+
down <https://github.com/jruby/jruby/issues/6104>`_. bson-ruby works around
584+
this and correctly floors the times when serializing on JRuby.
585+
586+
Because of this flooring, applications are strongly recommended to perform
587+
all time calculations using integer math, as inexactness of floating point
588+
calculations may produce unexpected results.
589+
590+
591+
Date And DateTime Instances
592+
---------------------------
593+
594+
BSON only supports storing the time as the number of seconds since the
595+
Unix epoch. Ruby's ``Date`` and ``DateTime`` instances can be serialized
596+
to BSON, but when the BSON is deserialized the times will be returned as
597+
``Time`` instances.
564598

565599

566600
Regular Expressions

0 commit comments

Comments
 (0)