Wednesday, July 16, 2014

Ruby - What quarter a date is in

I have a report i have to generate every week and it requests all items of a particular status since the begining of the current quarter. Everyone like to say "Just use activerecord!". Fuck you.

Here is the simple ruby code that will do it:

require 'Date'
def whatQuarter(date)
  thisYear = Time.new.year #just a filler year
  if    (Date.parse("#{thisYear}-01-01")..Date.parse("#{thisYear}-03-31")).cover?(date) #date range for quarter1
    return 'Q1'
  elsif (Date.parse("#{thisYear}-04-01")..Date.parse("#{thisYear}-06-30")).cover?(date)
    return 'Q2'
  elsif (Date.parse("#{thisYear}-07-01")..Date.parse("#{thisYear}-09-30")).cover?(date)
    return 'Q3'
  elsif (Date.parse("#{thisYear}-10-01")..Date.parse("#{thisYear}-12-31")).cover?(date)
    return 'Q4'
  end
end
def sameQuarter?(date1, date2)
  if whatQuarter(date1) == whatQuarter(date2)
    return true
  else
    return false
  end
end


I'm sure there is something retarded about that code but it seems to work for me :/

EDIT:

I shortened everything and made it easier on the eyes:

require 'Date'
def whatQuarter(date)
  thisYear = Time.new.year #just a filler year
  case    
    when (Date.parse("#{thisYear}-01-01")..Date.parse("#{thisYear}-03-31")).cover?(date) then return 'Q1'
    when (Date.parse("#{thisYear}-04-01")..Date.parse("#{thisYear}-06-30")).cover?(date) then return 'Q2'
    when (Date.parse("#{thisYear}-07-01")..Date.parse("#{thisYear}-09-30")).cover?(date) then return 'Q3'
    when (Date.parse("#{thisYear}-10-01")..Date.parse("#{thisYear}-12-31")).cover?(date) then return 'Q4'
  end
end

def sameQuarter?(date1, date2)
  whatQuarter(date1) == whatQuarter(date2) ? true : false
end

No comments:

Post a Comment