上传 CSV 文件时如何将 UTC 转换为人类可读格式

How to convert UTC to human readable format when uploading CSV files

上传 CSV 文件时如何将 UTC 格式转换为人类可读格式。

下面是我的Model & Controller,一切正常,CSV文件上传正常。

我需要在上传 CSV 文件时将 UTC 转换为人类可读格式,这在 Ruby 和 Rails 上可行吗?我什至不知道该怎么做。

型号

def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
        Product.create! row.to_hash
    end
end

控制器

def import
    Product.import(params[:file])
    redirect_to root_url
end

CSV 文件

-----------------------------
| name |      date_utc     |
-----------------------------
| John | 13123193563116372 |

DB Table

--------------------------------------
| id | name | date_utc | created_at |
--------------------------------------
|    |      |          |            |
--------------------------------------

这可能对你有帮助:

 CSV.foreach(file.path, headers: true) do |row| 
   product = Product.new
   product.name = row[0]
   product.date_utc = Time.at(row[1])
   product.save
 end

这是我去掉最后一位数字 (2) 并假设时间戳包括微秒后得到的结果:

Time.at(1312319356311637 / (1000 * 1000)).utc.to_datetime
# => 2011-08-02T21:09:16+00:00

那么您的 CSV 解析将如下所示:

CSV.foreach(file.path, headers: true) do |row|
  # Assuming it is a 17 digit number, we divide by 10 to remove the last digit.
  parsed_time = Time.at(row[1] / (10 * 1000000)).utc.to_datetime
  Product.create!(name: row[0], date_utc: parsed_time)
end

请注意,此解决方案仅在 date_utc 的长度为 17 位时有效。你会失去原来的精度。 如果这个假设是正确的,我强烈建议与你从中获取数据的人进行交叉核对。

我自己的解决方案

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
     p_hash = Product.new
     p_hash.name = row[0]
     p_hash.date_utc = Time.at(row[1].to_i).strftime("%B %e, %Y at %I:%M :%S %p")
     p_hash.save
  end
end

我考虑了时间戳数字长度。

感谢大家的参与。