2017-08-01 18 views
1

我正在使用Rails 5.0.1。我用下面的代碼輸出我的表中的數據,以CSV格式...在Rails中,如何在CSV文件中以毫秒爲單位輸出我的日期?

def self.to_csv(from_date, to_date) 
    attributes = %w{index_date value} #customize columns here 
    values = CryptoIndexValue.where('index_date >= ? and index_date <= ?', from_date, to_date) 
            .order(index_date: :desc) 

    CSV.generate(headers: true) do |csv| 
     csv << attributes 

     values.each do |value| 
     csv << attributes.map{ |attr| value.send(attr) } 
     end 
    end 
    end 

的問題是,當我的日期(一個Postgres 9.5時間戳列)輸出,它是作爲

2017-08-01 20:00:09 UTC 
輸出

我希望它以毫秒爲單位獲得輸出。如何調整上述內容以毫秒爲單位輸出時間,而不是默認的日期格式?

回答

1

你可以簡單地調用.to_i一個DateTime對象:

timestamp = DateTime.now.to_i 
# => 1501617998 
DateTime.strptime(timestamp.to_s, '%s') 
# => Tue, 01 Aug 2017 20:07:10 +0000 

時間戳是紀元以來的秒數。乘以一千,你會得到毫秒。

在你的情況,你必須做一個鉤子這種情況:

attr_values = attributes.map do |attr| 
    attr_value = value.send(attr) 
    attr_value = attr_value.to_i * 1000 if attr_value.is_a?(DateTime) 
    attr_value 
end 
csv << attr_values 

這意味着每次一個屬性返回一個DateTime對象,它會如果你想只篩選轉化爲時間戳* 1000。幾個attrs轉換日期時間 - >時間戳,測試attr與白名單,而不是測試attr_value的類。

+0

我不清楚我會在那裏提供的代碼。我使用行「csv << attributes.map {| attr | value.send(attr)}」將行輸出到csv「 – Dave

+0

您必須在輸出CSV之前爲某些值創建鉤子。我將在一秒內更新我的代碼 – MrYoshiji

+0

在我的情況下,這個類是「ActiveSupport :: TimeWithZone」。代替這一切使一切正常。 – Dave

相關問題