【问题标题】:Working with datetime in Rails在 Rails 中使用日期时间
【发布时间】:2010-11-18 14:18:03
【问题描述】:

如何在有/没有TimeZone影响的情况下仅从datetime对象(准确地说是post.created_at)中正确提取时间?如何提取daymonthyear 值?如何通过自定义模式提取day/month/year(是否可能)?

【问题讨论】:

    标签: ruby-on-rails ruby datetime time


    【解决方案1】:

    字符串格式的时间:

    post.created_at.strftime("FORMAT STRING HERE")
    # Without the influence of time-zone: I take it that you want UTC
    post.created_at.utc.strftime("FORMAT STRING HERE")
    

    strftime 文档的链接: http://ruby-doc.org/core/classes/Time.html#method-i-strftime

    获取小时、分钟和秒值:

    post.created_at.hour
    post.created_at.min
    post.created_at.sec
    

    【讨论】:

    • 射击,这正是我需要的!谢谢!
    • 简要说明、示例代码和文档链接。一个出色的答案!
    【解决方案2】:
    <%= l(@issue.created_at, format: :your_format) %>
    

    您必须在语言环境 YAML (app/config/locale/country_id.yml) 中声明

    time:
     formats:
      your_format: '%d %b. %Y'
      your_another_format: '%I:%M'
    

    日期格式应该在你的 i18n YAML 定义文件中声明以便于配置,其他日期格式可以在这里找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2014-03-12
      相关资源
      最近更新 更多