【问题标题】:Rails 5 how to add the HH:MM (string) in created_at?Rails 5如何在created_at中添加HH:MM(字符串)?
【发布时间】:2020-06-29 14:23:26
【问题描述】:

我有时间以字符串格式 05:50(Hours: Minutes) 我想将其添加到数据库中的 created_at(Wed, 16 Nov 2016 14:04:37 IST +05:30) 字段中。

我需要 14:04:37(HH:MM:SS) + 05:50(HH:MM)

我已经尝试过使用 strftime 方法,但没有成功。

我该怎么做?

【问题讨论】:

  • 这是我需要遵循的业务规则。
  • 我只需要在 created_at 字段中添加时间,那么我可以将它们都转换为秒然后添加它们吗?
  • @max - 询问 OP 试图完成什么并收到“因为”的等价物(又名“这是我需要遵循的业务规则”)。我之所以费心回应是因为我有一个很长的过程正在运行。不会再犯这种错误了。

标签: ruby-on-rails ruby datetime time


【解决方案1】:

使用ActiveSupport::Duration

string = '05:50'  
duration = ActiveSupport::Duration.parse(
  # converts string into a ISO8601 duration
  "PT" + ['H', 'M'].zip(string.split(':')).join  
)
puts duration.since(model.created_at) # 5 hours and 50 minutes in the future

并不是说这实际上并没有更新任何内容,因为您的问题非常模糊。如果您想更新现有记录,您需要调用:

model.update(created_at: duration.since(model.created_at))

对于新记录,您也许可以在生命周期内使用回调来更改它:

class MyModel < ActiveRecord::Base
  attribute_accessor :advance_by
  before_validate :advance_created_at, if: ->{ advance_by.present? }

  private
  def advance_created_at
    duration = ActiveSupport::Duration.parse(
        # converts string into a ISO8601 duration
        "PT" + ['H', 'M'].zip(@advance_by.split(':')).join  
    )
    self.advance_by = nil # prevents this from happening repeatedly
    self.created_at = duration.since(created_at)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    相关资源
    最近更新 更多