我正在尝试从一组哈希中计算平均时间。这是数组。
array = [
{"startTime"=>"2015-12-05T07:49:30.000Z", "endTime"=>"2015-12-05T15:56:30.000Z"},
{"startTime"=>"2015-12-04T07:02:30.000Z", "endTime"=>"2015-12-04T14:59:30.000Z"},
{"id"=>"5660614e8a3b090700bad845", "userId"=>"55cd59542d98600100397c12", "day"=>"2015-12-03", "startTime"=>"2015-12-03T06:02:32.000Z", "endTime"=>"2015-12-03T13:38:32.000Z"},
{"startTime"=>"2015-12-02T09:17:33.000Z", "endTime"=>"2015-12-02T15:27:33.000Z"},
{"startTime"=>"2015-12-01T05:45:36.000Z", "endTime"=>"2015-12-01T13:50:36.000Z"}
]
我正在尝试获取平均startTime和endTime。到目前为止,这是我尝试过的。
avg = Time.at(array.map {|x| x['startTime']}.reduce(:+).to_f / array.size.to_i)
我得到的结果是1969-12-31 16:06:43 -0800。这是不正确的。
require 'time'
array = [
{"startTime"=>"2015-12-05T07:49:30.000Z", "endTime"=>"2015-12-05T15:56:30.000Z"},
{"startTime"=>"2015-12-04T07:02:30.000Z", "endTime"=>"2015-12-04T14:59:30.000Z"},
{"id"=>"5660614e8a3b090700bad845", "userId"=>"55cd59542d98600100397c12", "day"=>"2015-12-03", "startTime"=>"2015-12-03T06:02:32.000Z", "endTime"=>"2015-12-03T13:38:32.000Z"},
{"startTime"=>"2015-12-02T09:17:33.000Z", "endTime"=>"2015-12-02T15:27:33.000Z"},
{"startTime"=>"2015-12-01T05:45:36.000Z", "endTime"=>"2015-12-01T13:50:36.000Z"}
]
times = array.map{|el| el['startTime']}.map{|el| Time.parse(el) }
#=> [2015-12-05 07:49:30 UTC, 2015-12-04 07:02:30 UTC, 2015-12-03 06:02:32 UTC, 2015-12-02 09:17:33 UTC, 2015-12-01 05:45:36 UTC]
average_time = Time.at(times.map(&:to_f).inject(:+) / times.size)
#=> 2015-12-03 08:11:32 +0100
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句