3

I have a column called test_date, type datetime in General Exam table. I built a form to create and update GeneralExam, on form, I allow User choose a date and time throught jQuery UI Datepicker.

After user choose date and time, it will displayed in textfield, like:

25-11-2012 16:30

It is my current time. When I run in console, I see the test_date was saved in database is:

2012-11-25 09:30:00

And when I get object GeneralExam, and get test_date value, it is:

g = GeneralExam.last
g.test_date
=> Sun, 25 Nov 2012 16:30:00 ICT +07:00

I think test_date is converted, because I set up in application.rb is:

config.time_zone = 'Hanoi'

But when I update a General Exam on form, it still display the time was saved in database, not my local timezone, it means it display:

2012-11-25 09:30:00

But I want it is like what I chose on form:

25-11-2012 16:30:00

How can I set up for display datetime column in local time?

And I think the order of date was reversed, when I choose date, it is 25-11-2012, but when it displayed it was 2012-11-25, Why it reversed the order?

Thanh
  • 8,219
  • 5
  • 33
  • 56

2 Answers2

5

After few hours I search on google and stackoverflow, I think I found what I want. I have looked at this question and find some information about strftime method. This is what information I need to solve my problem.

First, How to display datetime was saved in UTC as local time when display it:

Value was saved:                             2012-11-25 09:30:00

Value I want display on form (ICT +7:00):    25-11-2012 16:30:00

To display value I want, I used this on form (I used simple_form):

<%= f.input :test_date, as: :string, label: false, input_html: { id: "datetime_picker", value: f.object.test_date.strftime("%d-%m-%Y, %H:%M") } %> 

I have got value in database and format it by:

value: f.object.test_date.strftime("%d-%m-%Y, %H:%M") } %> 

And when I want display test_date in table data, I also used strftime("%d-%m-%Y, %H:%M") to display datetime format as I want.

Community
  • 1
  • 1
Thanh
  • 8,219
  • 5
  • 33
  • 56
0

The proper setting is related with your Rails config , but also with your DB config . There is a Railscast , explaining how to avoid most of the gotchas . For consistency all the dates and times are saved in the database in UTC . The conversion is made by Rails config , depending on your config.time_zone . In this case you should try :

Time.zone.now

which takes in account the configuration in Rails and is different from:

Time.now 
R Milushev
  • 4,295
  • 3
  • 27
  • 35
  • I don't want to get the current time, but I want display the time saved in database in local. After going around, I found solution, I will post it as answer :) – Thanh Nov 25 '12 at 11:29