0

我有以下数组:

open_emails = [["2012-04-21", 5], ["2012-04-20", 1], ["2012-04-22", 4]];

但我希望它采用以下格式:

open_emails = [[4545446464, 5], [35353535, 1], [353535353535, 4]];

IE。以毫秒为单位的日期

谢谢

4

2 回答 2

4

您可以使用to_timeto_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] }
于 2012-05-07T09:28:09.917 回答
2

如果您没有#to_time方法(旧 Ruby),您可以手动转换它(使用Time#local),或者执行以下操作:

Date.parse(s).strftime('%s').to_i

或者,完全跳过Date,并使用

Time.local(*s.split('-').map{|e| e.to_i}).to_i
于 2012-05-07T10:21:20.980 回答