【问题标题】:Rails how to remove UTC offset text ('UTC') from a dateTime leaving only the DateTime?Rails如何从dateTime中删除UTC偏移文本('UTC'),只留下DateTime?
【发布时间】:2012-06-11 18:33:55
【问题描述】:

我有一个工具集,可以将数据库中的所有内容存储为 UTC。在表单上,​​我有一个带有附加 jQuery 日期 + 时间选择器的文本字段。

在该文本字段中,日期时间戳(带 UTC 偏移量)将显示为:

<%= f.text_field :report_time, :size => 22  %>
    2012-06-05 15:55:50

但是,我需要在 EST 中选择此表单。所以我需要将它转换为表单,然后在提交表单时。此问题仅特定于执行“编辑”操作时(字段中已存在时间)。如果我做任何加法或减法,“UTC”会卡在表单文本字段的末尾:

@report.report_time = @report.report_time - 5.hours
=>2012-06-05 10:55:50 UTC

此时,我正在使用的 jQuery DateJS dateparse 函数将停止工作,因为它不理解保存日期时间的文本字段中的“UTC”文本。

如何获取 db UTC 时间并添加/减去小时数而不会在表单中删除“UTC”,或者如何删除 UTC offest 信息,只留下原始 dateTime 信息?

我该怎么做:

@report.report_time = @report.created_at - 5.hours
=>2012-06-05 10:55:50 UTC
#  do something here to strip " UTC" off the dateTime   ??
=>2012-06-05 10:55:50

谢谢! Rails 2.3.5 / Ruby 1.8.7

【问题讨论】:

  • 也许只是放手,并在 Document 上使用 JS 函数准备转换文本(例如在文本字段中去除最后 4 个字符) - 或者使用 text_field 标签并指定字段的值?

标签: ruby-on-rails


【解决方案1】:

如果不希望使用默认表示,请使用 strftime 函数直接设置字段的值。

<%= f.text_field :report_time, :size => 22, :value =>"...." %>

http://ruby-doc.org/stdlib-1.8.7/libdoc/date/rdoc/DateTime.html#method-i-strftime

您可能想查看此链接,了解如何通过表单构建器更自然地使用日期/时间。

http://guides.rubyonrails.org/form_helpers.html#using-date-and-time-form-helpers

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 2016-08-29
    • 2011-03-22
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多