日期时间不允许另外毫秒,除非UTC的

问题描述 投票:1回答:1

我想毫秒添加到DateTime对象,发现它被忽略,只有在应用整数(使用值超过1.0时)。

正如你所看到的,使用一个Time对象或调用.utc上的日期时间产生正确的结果:

utc_datetime = (DateTime.new(2018, 8, 8, 10, 24, 45.856).utc + 0.5.seconds).to_s(:ms_hr)
# => "2018-08-08 10:24:46.356"

non_utc_datetime = (DateTime.new(2018, 8, 8, 10, 24, 45.856) + 0.5.seconds).to_s(:ms_hr)
#=> "2018-08-08 10:24:46.856"

time = (Time.new(2018, 8, 8, 10, 24, 45.856) + 0.5.seconds).to_s(:ms_hr)
#=> "2018-08-08 10:24:46.356"

为什么?为什么一个标准的DATETIME忽略毫秒?什么是.utc呼叫做这突然让表现为需要的对象?

ruby-on-rails ruby datetime ruby-on-rails-5
1个回答
2
投票

一个DateTime,你会得到什么从调用.utc它是两个不同的对象,所以,当你添加了一些每个,每个这些对象可以强迫其他对象,因为它认为合适的。

DateTime是一个DateTime对象,而在铁轨至少调用.utc DateTime对象上会返回一个Time对象。

在日期时间的情况下,它看起来像它期待值+是在天,而时间预计值是在几秒钟。

例如

(DateTime.new(2018, 8, 8, 10, 24, 45.856) )
2.4.1 :050 > (DateTime.new(2018, 8, 8, 10, 24, 45.856) )
 => #<DateTime: 2018-08-08T10:24:45+00:00 ((2458339j,37485s,856000000n),+0s,2299161j)> 

# add 1 day
2.4.1 :051 > (DateTime.new(2018, 8, 8, 10, 24, 45.856) + 1 )
 => #<DateTime: 2018-08-09T10:24:45+00:00 ((2458340j,37485s,856000000n),+0s,2299161j)> 

# add 100ms
2.4.1 :052 > (DateTime.new(2018, 8, 8, 10, 24, 45.856) + 0.1/60.0/60.0/24.0)
 => #<DateTime: 2018-08-08T10:24:45+00:00 ((2458339j,37485s,956000000n),+0s,2299161j)> 

# add 1s
2.4.1 :053 > (DateTime.new(2018, 8, 8, 10, 24, 45.856) + 1.0/60.0/60.0/24.0)
 => #<DateTime: 2018-08-08T10:24:46+00:00 ((2458339j,37486s,856000000n),+0s,2299161j)> 

演示什么另一个例子是怎么回事:

2.4.1 :081 > t = Time.now
 => 2019-02-02 09:20:23 -0500 

# adding 1 to a time object adds a second
2.4.1 :082 > (t + 1).to_i - t.to_i
 => 1 

2.4.1 :083 > d = DateTime.now
 => #<DateTime: 2019-02-02T09:20:58-05:00 ((2458517j,51658s,883341147n),-18000s,2299161j)> 

# adding 1 to a DateTime object add 60*60*24 = 86400 seconds, ie 1 day
2.4.1 :085 > (d + 1).to_time.to_i - d.to_time.to_i
 => 86400 
© www.soinside.com 2019 - 2024. All rights reserved.