【问题标题】:Rails Time Column Not Respecting MinutesRails 时间列不尊重分钟
【发布时间】:2021-04-24 23:03:03
【问题描述】:

我在 Rails 6 中的一个模型上有一个Time 列。我在数据库中保存的时间与strftime 的结果不匹配存在问题。这是我的byebug 输出:

(byebug) record.end
Fri, 31 Dec 1999 18:00:00 CST -06:00
(byebug) record.end.strftime("%I:%m %P")
"06:12 pm"

如您所见,除非我致电 strftime,否则不会遵守会议记录。我怎样才能解决这个问题?我希望在record.end 中计算分钟数,以便我可以使用该列进行计算。目前,一切都休息 12 分钟。

这是我为使其成为Time 列而进行的迁移。该列最初是DateTime

class ChangeStartAndEndColumnTypesOnTimeRecord < ActiveRecord::Migration[6.0]
  def change
    change_column :time_records, :start, :time
    change_column :time_records, :end, :time
  end
end

【问题讨论】:

  • 您使用的是哪个数据库? mysql?
  • @Mshka PostgreSQL

标签: ruby-on-rails ruby ruby-on-rails-6


【解决方案1】:

一个常见的错误,%m 给出了月份。您需要使用 %M 几分钟。

【讨论】:

    【解决方案2】:

    我更喜欢使用DateTime 作为列类型。

    您的代码record.end 实际上不是字符串,而是整数(unix 时间戳)。如果您只想要 minutes 部分,您可以通过以下方式获得:

    # only get minutes
    record.end.strftime("%M")
    
    # get year, month, day , hour, minutes...
    record.end.strftime("%Y-%m-%d %H:%M:%S")
    
    => 2021-04-25 08:14:53
    

    如果你真的不喜欢每次需要'分钟'时都调用strftime,你可以在Rails中定义一个全局方法,比如

    (以下代码未在生产环境中测试,仅作说明用途)

    # in config/initializers/datetime.rb or something
    class DateTime
      def to_s
        this.strftime('%M')  # this will only output the minutes 
      end
    end
    

    【讨论】:

    • 你也搞混了。您在格式化整个日期时是正确的,但在访问分钟时是错误的。它必须是 %M,大写。
    • @eweb 哦,是的,你是对的,我更正了。
    猜你喜欢
    • 2022-10-30
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 2013-05-20
    相关资源
    最近更新 更多