Metal
Metal

Reputation: 455

Ruby on Rails - Handling of DateTime.current and User Input Time

I'm using Rails 3.2.9 with Postgres database and JRuby 1.7.12.

Application is running Ubuntu Server with GMT+7 Asia/Bangkok Time Zone.
config.time_zone is set to Bangkok
Postgres timezone is also set to Asia/Bangkok

In my invoice model, I have 2 datetime fields called document_date and movement_date

-> movement_date is generated by application using DateTime.current
-> document_date is input by the User (i.e 2014-07-28)

When User save the Invoice, both will be converted to UTC and saved into Database.

for movement_date, it is fine (as this is the expected behaviour)

for document_date, when it is convert to UTC, it will be saved as 2014-07-27 17:00.

How can I save document_date to 2014-07-28 00:00 into database without converting to UTC.

Your Help, Advise, Suggestion would be highly appreciated and Many Thanks in advance.

If there are any additional info I should add, kindly let me know.

EDIT: the field in postgresql for both is using Timestamp Without Time Zone

Upvotes: 1

Views: 825

Answers (1)

warantesbr
warantesbr

Reputation: 660

If i understood it correctly, you want the document_date (which is an user input) to be in UTC, rather than in your local time. Is it correct? If so, you'll have to change it manually, as Rails makes the assumption that you want it in your local time.

What you could do is set it manually, converting the date string to datetime (String#to_datime), just before the object saving on your controller. Something like that:

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

String#to_datetime will create a UTC DateTime as long as the string doesn't have Time and TimeZone parts on it (ie: "2014-07-28 00:00:00 +0700" will be converted to Bangkok DateTime).

Upvotes: 1

Related Questions