rangalo
rangalo

Reputation: 5606

ruby DateTime.strftime shows wrong hour in the date

I have following code in my model

  def formatted_startdatetime
    unless startdatetime.nil?
      startdatetime.strftime('%d.%m.%Y %H:%M Uhr')
    end
  end

  def formatted_startdatetime=(date_str)
    self.startdatetime = DateTime.strptime(date_str,'%d.%m.%Y %H:%M') unless date_str.blank?
  end

formatted_startdatetime is attr_accessor for original field startdatetime.

On the view, I use Jquery datetime plugin to select the datetime value.

In the database the values is as following for an example record. It is same as what is shown on the view.

| 5 | Letzter Kontakt | 2011-02-03 09:00:00 | 2011-02-04 17:00:00 |
| 19 | NULL |
NULL | NULL | 2011-02-03 15:14:52 | 2011-02-03 15:14:52 | ddkk | 1 |

It is a mysql table the startdatetime is 2011-02-03 09:00:00.

But when I display it on the view with

  <b>Von:</b>
  <%= @activity.formatted_startdatetime unless @activity.startdatetime.blank? %><br/>

I see it as:

Von: 03.02.2011 10:00 Uhr

Why 1 hour is added to the actual time ? How can I fix this and get the same time back as I store ?

Upvotes: 1

Views: 1155

Answers (3)

Bulat
Bulat

Reputation: 262

For some reason I had this problem only in my test. I fixed it by explicitly specifying the UTC offset in the date I created:

@date = Time.new(2012, 12, 27, 20, 15, 0, "+00:00")
visit '/mypage'
expect(page).to have_content @date.strftime '%F %R'

Upvotes: 0

rangalo
rangalo

Reputation: 5606

Looks like the time is converted by rails.

It is the timezone configuration in config/environment.rb which has following line

config.time_zone = 'Berlin'

When I do following in the console, I get the time which is stored in the database

@activity.startdatetime_before_type_cast

Now I have two choices

  1. To change the timezone to UTC which will be wrong because I am in the time zone Europe/Berlin

  2. Print the date with @activity.startdatetime_before_type_cast

Which option is the best ?

Upvotes: 0

Thibaut Barr&#232;re
Thibaut Barr&#232;re

Reputation: 8873

I suspect your database stores dates as UTC+0, while you're probably in an UTC+1 country, so they get converted back at reading time.

Upvotes: 1

Related Questions