Will Taylor
Will Taylor

Reputation: 2304

DateTime turned to string by two methods

I am trying to compare two DateTime attributes in a view, which is after the attributes have been turned into strings. Unfortunately the objects are being turned into slightly different formatted strings, and so are never able to be equal. Any adea why?

Version A: 2015-11-12 00:00:00 +0000 
Version B: 2015-11-12T00:00:00+00:00

Context in my view:

options_for_select(dates, selected: (f.object.start ? f.object.start.change({hour: 0}).to_s : 0))

Here, dates generates Version A

  def dates(first_date=DateTime.now)
    first_date = date.midnight
    dates = []
    [*0..100].each do |i|
      dates << [(first_date + i.days).strftime("%a %d %b"), (first_date + i.days)]
    end
    dates
  end

f.object.start.change({min: 0}).to_s generates Version B

Update

It seems like 'optionising' the dates is modifying them.

Here's the HTML produced when turned to an option:

<option value="2015-11-12T14:41:15+00:00">Thu 12 Nov</option>

Here's the normal value:

<%= dates[3] %>

generates:

["Fri 13 Nov", Fri, 13 Nov 2015 00:00:00 +0000]

Upvotes: 2

Views: 40

Answers (1)

Yury Lebedev
Yury Lebedev

Reputation: 4015

The version B is time with timezone, the version A is without the timezone. I would suggest you to use Tome.zone.now instead of DateTime.now

And there is one more issue with your code: you can use the default value for the argument like this: def dates(first_date=DateTime.now), but you better not to. The problem is, that the DateTime.now will be executed, when your code will be loaded by the ruby interpreter, and the default value will not change anymore, not until you reaload your server.

So my suggestion would be to change the code to this:

def dates(start_time = nil)
  start_time = Time.zone.now if start_time.nil?
  first_date = date.midnight

Upvotes: 1

Related Questions