如何处理 POST 参数中的日期/时间? [英] How to handle date/times in POST parameters?

查看:102
本文介绍了如何处理 POST 参数中的日期/时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,Rails 的 config.time_zone 是 UTC.因此,created_atupdated_at 等字段以 UTC 格式保存.

By default, Rails' config.time_zone is UTC. So, fields like created_at, updated_at are saved in UTC.

现在,假设用户的时区是太平洋标准时间 (PST).

Now, presume user's time zone is Pacific Standard Time (PST).

为了在用户的时区中显示日期和时间,我将 Time.zone 设置为 PST.

In order to show dates and times in the user's time zone, I have set Time.zone to PST.

现在,当用户在表单中输入日期(在用户的本地时区,即 PST)时,控制器会根据 Time.zone 的设置接收该日期.

Now, when a user enters a date (in user's local time zone, which is PST) in a form, that date is received in the controller according to the setting of Time.zone.

但是,我想以 UTC 格式保存数据库中的所有时间.

But, I want to save all times in the database in UTC.

那么,我将如何将参数哈希中的任何日期/时间字段就地转换为 UTC?我想知道是否有解决方案可以让 Rails 自动进行转换?

So, how would I go about converting any date/time field in-place in the parameters hash to UTC? I'm wondering if there is a solution where Rails can do the conversion automatically?

我希望为任何日期时间字段接收的任何日期/时间都转换为 UTC,而不必在每个控制器中编写转换代码.

I would like that any date/time received for any datetime field be converted to UTC, without having to write the conversion code in every controller.

我通过将 Time.zone 设置为 太平洋时间(美国和加拿大) 以及东部时间(美国和加拿大) 进行测试,然后保存模型.两种情况下的 created_at 时间都是 UTC.这样就确认了设置 Time.zone 对 Rails 在 created_at 字段中保存的时间没有影响.该值仅受 config.time_zone 影响(如果未在 application.rb 中定义,则默认为 UTC)

I tested by setting Time.zone to Pacific Time (US & Canada) as well as to Eastern Time (US & Canada) and then saving a model. The created_at time in both cases was in UTC. So that confirms that setting Time.zone has no effect on what time is saved by Rails in the created_at field. That value is effected only by the config.time_zone (which if not defined in application.rb will default to UTC)

我对这一切感到很困惑!

I'm so confused by this all!

推荐答案

在数据库中,所有日期始终保存为 UTC.config.time_zone 参数为Time.zone 设置默认值,仅用于显示.所以你不需要做任何事情来获得你想要的行为,只需为用户正确设置 Time.zone,剩下的事情就交给 Rails.

In the database, all dates are always saved as UTC. The config.time_zone parameter is setting the default value for Time.zone, just for display. So you don't have to do anything to get the behavior you desire, just keep Time.zone set correctly for the user, and rails takes care of the rest.

这篇关于如何处理 POST 参数中的日期/时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆