gpt4 book ai didi

ruby-on-rails - 更改魔法列的时间戳 (Rails)

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

我想更改 rails (created_at, modified_at) 的魔法列的默认时间戳,而不是 2010-09-03 14:52:46 UTC 我想将其更改为 2010 年 9 月 10 日 02:52下午。或者至少以这种方式解析。

现在,我知道我可以通过操纵变量在 View 中做到这一点,但是没有更“简单的方式”我可以在模型中做到这一点,然后将其作为方法调用吗?

最佳答案

class YourModel < ActiveRecord::Base
def my_formated_date_time
created_at.strftime("%B %d, %Y at %I:%M %p")
end
end

或者您可以使用本地化格式。将此添加到您的 config/locale/your_locale.yml。恕我直言:这将是最railish 的方式。

your_locale:
time:
formats:
default: "%B %d, %Y at %I:%M %p"

然后在你看来这样做

<%=l @your_model.created_at %>
<!-- short for: -->
<%= I18n.localize @your_model.created_at %>

关于ruby-on-rails - 更改魔法列的时间戳 (Rails),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3637071/

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