Search code examples
rubydatedatetimetimedst

I am trying to subtract 3 hours from a method that I have created but I am getting an error


I have successfully created a DST method called dst_datechange that takes a date, is parsed out using Time.parse. It looks like this:

require 'time'
def dst_datechange(date)
  date = Time.parse(date.to_s) # if date.class.eql?(String)
  case
  when (date > Time.parse('March 11, 2018 2:00am')) && (date < 
Time.parse('November 4, 2018 2:00am'))
    date = Time.parse('November 4, 2018 2:00am')
    puts "the date rounded to november 4, 2018"
  when (date > Time.parse('November 4 2018, 2:00am')) && (date < 
Time.parse('March 10, 2:00am'))
    date = Time.parse('March 10, 2019 2:00am')
    puts "the date rounded to march 10 2019"
  when (date > Time.parse('March 10, 2019 2:00am')) && (date < 
Time.parse('November 3, 2019 2:00am'))
    date = Time.parse('November 3, 2019 2:00am')
  when (date > Time.parse('November 3, 2019 2:00am')) && (date < 
Time.parse('March 8, 2020 2:00am'))
    date = Time.parse('March 8, 2020 2:00am')
  when (date > Time.parse('March 8, 2020 2:00am')) && (date < 
Time.parse('November 1, 2020 2:00am'))
    date = Time.parse ('November 1, 2020 2:00am')
  else
    raise "The date #{date} does not match any dst date parameter"
  end
  date
  puts "the new DST date is #{date}"
end

and my "puts" displays this...

the date rounded to: november 4, 2018 
 the new DST date is now: 2018-11-04 02:00:00 -0600

Now that I am receiving the correct date, I have a step that takes that dst_datechange and performs a subtraction, however, I am getting an error that says:

TypeError: no implicit conversion of Integer into Array

I am not sure what I am doing wrong but I know its most likely a formatting issue where I am trying to subtract a date time object with just a time object. here is my step below where the stacktrace is pointing the failure at:

  date = (dst_datechange(Time.now) - (60*60*3))
  puts "the date is now adjusted 3 hours back from 2:00am:  #{date} "
end

I am unsure how to format that (60*60*3) to subtract 3 hours from that new November 2018-11-04 02:00:00 -0600 date and basically roll it back to 2018-11-03 23:00:00 -0600


Solution

  • Your method def dst_datechange(date) doesn't return the date you want it to, but instead puts your string.

    When you call that in your second part, dst_datechange(Time.now), that doesn't return the date, but the return value for the last puts.

    Try calling 'date' again after your final puts in your dst_datechange method:

    when (date > Time.parse('March 8, 2020 2:00am')) && (date < Time.parse('November 1, 2020 2:00am'))
    date = Time.parse ('November 1, 2020 2:00am')
      else
        raise "The date #{date} does not match any dst date parameter"
      end
      puts "the new DST date is #{date}"
      date
    end