【问题标题】:'Time.at(seconds)' gives different time than 'fractions(seconds/60, seconds%60)''Time.at(seconds)' 给出的时间与 'fractions(seconds/60, seconds%60)' 不同
【发布时间】:2017-06-06 05:56:43
【问题描述】:

我正在执行这段代码:

t = DateTime.strptime('1:00:23', '%H:%M:%S')
t1 = DateTime.strptime('2:02:40', '%H:%M:%S')
t2 = t1.to_time - t.to_time
time_new = "#{(t2/3600).to_i}" + ":" +"#{((t2/60)%60).to_i}" + ":" + "#{(t2%60).to_i}"
time_units = time_new.split(':')

我明白了:

Time.at(t2).strftime("%H:%M:%S")
# => 06:32:17
"#{time_units[0]} hours, #{time_units[1]} minutes and #{time_units[2]} seconds"
# => 1 hours, 2 minutes and 17 seconds

这是非常不同的。为什么Time.at(seconds) 增加了 5 小时 30 分钟?

【问题讨论】:

  • 试试Time.zone.at(t2).strftime("%H:%M:%S")
  • 因为你的时区
  • @Md.FarhanMemon 尝试了“Time.zone.at(t2).strftime("%H:%M:%S")”。它给了我未定义的方法 `zone' for Time:Class (NoMethodError)
  • 对,您需要在application.rb 中设置您的时区,例如config.time_zone = 'Mumbai'
  • 我没有在 Rails 上使用 ruby​​,它只是一个简单的 ruby​​ 代码

标签: ruby


【解决方案1】:

Time.at(seconds) 为什么要加 5 小时 30 分钟?

因为你在比较苹果和橘子。

DateTime.strptimeUTC 中返回 DateTime 实例。如果您不提供日期,则使用今天的日期

DateTime.strptime('01:00:23')
#=> Tue, 06 Jun 2017 01:00:23 +0000
#   ^^^^^^^^^^^^^^^^          ^^^^^
#         today                UTC

Time.at 根据自纪元(1970 年 1 月 1 日)的秒数返回您本地时区中的Time 实例:

Time.at(1 * 3600 + 23)
#=> 1970-01-01 02:00:23 +0100
#   ^^^^^^^^^^          ^^^^^
#   not today          not UTC

【讨论】:

    猜你喜欢
    • 2021-08-10
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多