Saving datetime in UTC isn't accurate sometimes

后端 未结 3 1587
隐瞒了意图╮
隐瞒了意图╮ 2021-02-01 21:34

In general, best practice when dealing with dates is to store them in UTC and convert back to whatever the user expects within the application layer.

That doesn\'t neces

3条回答
  •  时光取名叫无心
    2021-02-01 22:25

    This may sound a bit out there, but I have dealt with similar issues with a recent application I was tasked with - but on the opposite side - when I run an ETL to load data for the application, dates from the source are stored in EST. Rails believes that it is UTC when serving the data, so for that, I converted the dates back to UTC using P/SQL. I did not want these dates to be different than the other date fields within the app.

    Option A In this case, could you capture the user timezone at creation, and send that back as a hidden field in the form? I am still learning RoR, so am not sure on the "proper" way to do this, but right now I would do something like this:

    Example (I tested this, and it will submit the offset (minutes) in a hidden field):

    <%= f.hidden_field :offset %>

    If you then send utcDiff along with the user selected date, you could calculate the UTC date before storing. I suppose you could add that to the model as well if that data is necessary to know at a later date.

    I think that no matter how this is done, there will always be slight area for confusion, unless the user is capable of providing the proper information, which leads me to...

    Option B: You could, instead of a hidden field, provide a select list (and to be friendly, default it to the users' local offset), to allow them to provide the zone for which their date is specified in.

    Update - TimeZone select I've done some research, and it looks like there is already a form helper for a time zone select box.

提交回复
热议问题