0
我有以下陣列:我怎麼能轉換日期此數組中的最新類型的對象在Ruby中
open_emails = [["2012-04-21", 5], ["2012-04-20", 1], ["2012-04-22", 4]];
但我希望它是格式:
open_emails = [[4545446464, 5], [35353535, 1], [353535353535, 4]];
即。以毫秒爲單位的日期
感謝
我有以下陣列:我怎麼能轉換日期此數組中的最新類型的對象在Ruby中
open_emails = [["2012-04-21", 5], ["2012-04-20", 1], ["2012-04-22", 4]];
但我希望它是格式:
open_emails = [[4545446464, 5], [35353535, 1], [353535353535, 4]];
即。以毫秒爲單位的日期
感謝
您可以使用to_time
和to_i
方法
require 'date' # not required if you're using rails
open_emails = [["2012-04-21", 5], ["2012-04-20", 1], ["2012-04-22", 4]]
open_emails.map { |s, i| [Date.parse(s).to_time.to_i, i] }
# => [[1334959200, 5], [1334872800, 1], [1335045600, 4]]
在Ruby 1.8沒有to_time
方法,相反,您可以使用Time.mktime
:
open_emails.map { |s, i| [Time.mktime(*s.split('-')).to_i, i] }
如果您沒有#to_time
方法(較舊的Ruby),則可以手動將其轉換(使用Time#local
),或做這樣的事情,而不是:
Date.parse(s).strftime('%s').to_i
或者跳過Date
乾脆,並使用
Time.local(*s.split('-').map{|e| e.to_i}).to_i
不使用Ruby工作1.8.7嗎? –
我更新了Ruby 1.8.7的答案 - 希望可以幫助 – Matt
非常感謝 – chell