gpt4 book ai didi

ruby-on-rails - 从数组计算时间并转换为时区

转载 作者:数据小太阳 更新时间:2023-10-29 08:03:17 25 4
gpt4 key购买 nike

我有一个 bed_times 数组,其中包含 UTC 格式的 Time 实例:

bed_times = [
Time.utc(2015, 12, 10, 5, 58, 24),
Time.utc(2015, 12, 9, 3, 35, 28),
Time.utc(2015, 12, 8, 6, 32, 26),
Time.utc(2015, 12, 7, 1, 43, 28),
Time.utc(2015, 12, 5, 7, 49, 30),
Time.utc(2015, 12, 04, 7, 2, 30)
]
#=> [2015-12-10 05:58:24 UTC,
# 2015-12-09 03:35:28 UTC,
# 2015-12-08 06:32:26 UTC,
# 2015-12-07 01:43:28 UTC,
# 2015-12-05 07:49:30 UTC,
# 2015-12-04 07:02:30 UTC]

我正在尝试获取平均就寝时间,但我没有得到正确的结果

ave = Time.at(bed_times.map(&:to_f).inject(:+) / bed_times.size)

结果是

2015-12-07 01:26:57 -0800

这是不正确的。另外,我想将平均时间转换为不同的时区

我试过了

Time.zone = 'Pacific Time (US & Canada)'
Time.zone.parse(ave.to_s)
2015-12-07 01:26:57 -0800

这也不对。

最佳答案

您必须计算从午夜开始的平均值

一个不优雅(但快速)的解决方案可能是:

# Keep only time    
bed_times.map! { |bt| Time.parse(bt.split(" ")[1]) }

# calculate the gap from 00:00:00
gap_from_midnight = bed_times.map do |bt|
if bt > Time.parse("12:00:00")
gap = (bt.to_f - Time.parse("24:00:00").to_f)
else
gap = (bt.to_f - Time.parse("00:00:00").to_f)
end
gap.to_i
end

# average in sec
avg_in_sec = gap_from_midnight.inject(:+) / bed_times.size

# average in UTC time zone
avg = Time.at(avg_in_sec).utc # => 1970-01-01 05:26:57 UTC (result for bed_times array)

# average in PST time zone (see note)
avg_pst = Time.parse(avg.to_s).in_time_zone("Pacific Time (US & Canada)") # => Wed, 31 Dec 1969 21:26:57 PST -08:00 (result for bed_times array)

# Keep only time
avg_pst.strftime("%H:%M:%S") # => "21:26:57" (result for bed_times array)

使用您的bed_times 数组(值为字符串)

bed_times = [
"2015-12-10 05:58:24 UTC",
"2015-12-09 03:35:28 UTC",
"2015-12-08 06:32:26 UTC",
"2015-12-07 01:43:28 UTC",
"2015-12-05 07:49:30 UTC",
"2015-12-04 07:02:30 UTC"
]

平均值是:

  • 05:26:57 UTC 时区
  • 21:26:57 在 PST 区

用另一个像这样的数组

bed_times = [
"2015-12-10 01:00:00 UTC",
"2015-12-09 23:00:00 UTC",
"2015-10-19 18:00:00 UTC",
]

平均值是:

  • 22:00:00 UTC 时区
  • 14:00:00 在 PST 区

注意:.in_time_zone 是来自ActiveSupport::TimeWithZone 的助手 http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html

关于ruby-on-rails - 从数组计算时间并转换为时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34234337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com