ruby-on-rails – 在Rails中以毫秒为单位存储时间
发布时间:2020-12-17 02:10:01 所属栏目:百科 来源:网络整理
导读:我正在尝试在Rails中存储毫秒精度的时间戳,但是当我从数据库中检索记录时,该值会被抬高: record.time_stamp = Time.utc(2017,1,1.35) 保存前检查时间: record.time_stamp.strftime('%H:%M:%S.%L')= "01:01:01.350" record.time_stamp.usec= 350000record.t
我正在尝试在Rails中存储毫秒精度的时间戳,但是当我从数据库中检索记录时,该值会被抬高:
record.time_stamp = Time.utc(2017,1,1.35) 保存前检查时间: record.time_stamp.strftime('%H:%M:%S.%L') => "01:01:01.350" record.time_stamp.usec => 350000 record.time_stamp.to_f => 1483232461.35 保存并重新加载: record.save! record.reload 保存后检查时间: record.time_stamp.strftime('%H:%M:%S.%L') => "01:01:01.006" record.time_stamp.usec => 6108 record.time_stamp.to_f => 1483232461.0061078 record.read_attribute_before_type_cast("time_stamp") // Read raw value before type casting => "2017-01-01 01:01:01.35" 不知道这里发生了什么.存储在DB中的毫秒值是正确的,就像压缩之前的原始值一样(参见最后一行),它只是在重新投入Ruby Time时搞砸了. 笔记: >我意识到Ruby Time is precise to nanoseconds,while the DB is only precise to microseconds – 但我只是想节省毫秒,所以这不应该是一个因素. (规格:Rails / ActiveRecord 4.2.6,ruby 2.3.0,Postgres 9.5.0,OSX) 更新: 解决方法
我无法使用Rails 4.2.6和5.0.5(以及Ruby 2.3.1,Postgres 9.6.4)重现该问题
# Gemfile ruby '2.3.1' gem 'rails','4.2.6' gem 'pg' require 'active_record' # example.rb class Record < ActiveRecord::Base establish_connection adapter: 'postgresql',database: 'try_timestamp',username: 'postgres' connection.create_table table_name,force: true do |t| t.datetime :time_stamp end end time_stamp = Time.utc 2017,1.35 record = Record.new time_stamp: time_stamp p record.time_stamp.strftime('%H:%M:%S.%L') p record.time_stamp.usec p record.time_stamp.to_f record.save! record.reload p record.time_stamp.strftime('%H:%M:%S.%L') p record.time_stamp.usec p record.time_stamp.to_f # terminal command ? createdb try_timestamp ? bundle install ? bundle exec ruby example.rb "01:01:01.350" 350000 1483232461.35 "01:01:01.350" 350000 1483232461.3500001 您可以运行此示例并告诉问题是否在clear rails app上重现? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |