diff --git a/lib/fluent/time.rb b/lib/fluent/time.rb index dbe1ddee35..f97f89b61a 100644 --- a/lib/fluent/time.rb +++ b/lib/fluent/time.rb @@ -69,6 +69,19 @@ def to_s @sec.to_s end + begin + # ruby 2.5 or later + Time.at(0, 0, :nanosecond) + + def to_time + Time.at(@sec, @nsec, :nanosecond) + end + rescue + def to_time + Time.at(@sec, @nsec / 1000.0) + end + end + def to_json(*args) @sec.to_s end diff --git a/test/test_event_time.rb b/test/test_event_time.rb index 0c74d209e9..581a276e57 100644 --- a/test/test_event_time.rb +++ b/test/test_event_time.rb @@ -36,6 +36,19 @@ class EventTimeTest < Test::Unit::TestCase assert_equal('100', "#{time}") end + test '#to_time' do + time = Fluent::EventTime.new(@now.to_i, @now.nsec).to_time + assert_instance_of(Time, time) + assert_equal(@now.to_i, time.to_i) + begin + ::Time.at(0, 0, :nanosecond) + assert_equal(@now.nsec, time.nsec) + rescue + # Time.at(@sec, @nsec / 1000.0) sometimes cause 1 diff error in nsec by 1000.0 + assert_in_delta(@now.nsec, time.nsec, 1) + end + end + test '#to_json' do time = Fluent::EventTime.new(100) assert_equal('100', time.to_json)