简体   繁体   中英

Save time string with timezone in Rails

I have a database table with a column of type time . So far, I've been saving a "zoneless" time, eg 4:00pm . I've been accepting this string "as is" and Rails has been happily saving this time string properly in the database.

I'm now having the need to save this value with a time zone. I'd like to somehow take a 4:00pm time in EDT and save it in the database as UTC, 8:00pm . (I realize that this 4:00pm was originally being saved as 4:00pm UTC.)

I don't particularly care how this 4:00pm EDT time gets saved as UTC, although I'd prefer to take advantage of Rails' native behavior and not make my code more complicated than it needs to be.

It may be important to know that my Rails app is in the form of an API, so I won't be using any sort of form helpers or anything like that. I have to simply accept a string. I can, however, control the format in which that string is sent.

So, so summarize, how can I save a string like 4:00pm EDT as 8:00pm UTC in the database?

Assuming that ruby's Time constructor interpreted the timezone correctly, you just need to call the utc method on the created object. Like so:

t = Time.parse("4:00pm EDT")
t.utc

If this date is set during a mass assignment, you may want to set a before_save handler on the model in order to set the time to UTC.

Edit by OP :

This is the exact form my solution ended up taking:

def earliest_arrival_time=(time)
  begin
    write_attribute(:earliest_arrival_time, Time.parse(time.to_s).utc)
  rescue
    write_attribute(:earliest_arrival_time, time)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM