【问题标题】:Ruby on Rails - Handling of DateTime.current and User Input TimeRuby on Rails - 处理 DateTime.current 和用户输入时间
【发布时间】:2014-09-19 06:39:37
【问题描述】:

我正在使用带有 Postgres 数据库和 JRuby 1.7.12 的 Rails 3.2.9。

应用程序正在运行 GMT+7 亚洲/曼谷时区的 Ubuntu 服务器。
config.time_zone 设置为曼谷
Postgres 时区也设置为 Asia/Bangkok

在我的发票模型中,我有 2 个日期时间字段,分别称为 document_date 和 move_date

-> 运动日期由应用程序使用 DateTime.current 生成
-> document_date 由用户输入(即 2014-07-28)

当用户保存发票时,两者都将转换为 UTC 并保存到数据库中。

对于运动日期,很好(因为这是预期的行为)

对于document_date,当它转换为UTC时,它将被保存为2014-07-27 17:00。

如何在不转换为 UTC 的情况下将 document_date 保存到 2014-07-28 00:00 到数据库中。

我们将非常感谢您的帮助、建议和建议,并在此先感谢您。

如果我需要添加任何其他信息,请告诉我。

编辑:postgresql 中的字段都使用 Timestamp without Time Zone

【问题讨论】:

  • 好吧,如果 document_date 字段被定义为 date 而不是 datetimetimestamp 它不会节省时间部分

标签: ruby-on-rails postgresql jrubyonrails


【解决方案1】:

如果我理解正确,您希望 document_date(这是用户输入)采用 UTC,而不是您的本地时间。这是正确的吗?如果是这样,您将不得不手动更改它,因为 Rails 会假设您在本地时间需要它。

您可以手动设置它,将日期字符串转换为日期时间 (String#to_datime),就在控制器上保存对象之前。类似的东西:

def create
  @invoice = Invoice.new(params[:invoice])
  @invoice.document_date = params[:invoice][:document_date].to_datetime
  @invoice.save
end

String#to_datetime 将创建一个 UTC DateTime,只要字符串上没有 Time 和 TimeZone 部分(即:“2014-07-28 00:00:00 +0700”将转换为 Bangkok DateTime) .

【讨论】:

  • 所以如果我收到带有 TimeZone 部分的 DateTime(即:“2014-07-28 00:00:00 +0700”),那么我应该使用 params[:invoice][:document_date].to_datetime .strftime("%Y-%m-%d").to_datetime?
  • @Thetnaung 如果你只想要日期部分,你可以做的是:"2014-07-28 00:00:00 +0700".to_date。如果您希望将其转换为 DateTime 类的实例,请在末尾添加.to_datetime
猜你喜欢
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2011-03-21
  • 2018-03-01
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多