Springe zum Inhalt

Count future events

The problem

My choir wants to advertise the number of rehearsals before the next concert. We have a list of rehearsal dates and need to count those who have not yet passed.

The solution (JavaScript)

<div id="result"></div>
function dateDtoE(s)
  h = s.split(".");
  return '20' + h[2] + '-' + ('0'+h[1]).substr(-2) + '-' + ('0'+h[0]).substr(-2); 
var dates2go = [ '28.6.18','5.7.18','12.7.18','19.7.18','26.7.18','2.8.18','9.8.18','30.8.18'];

var count = 0;
var now = new Date();
var i = dates2go.length;
  h = dateDtoE(dates2go[i]);
  var test = new Date(dateDtoE(dates2go[i]) + 'T22:00:00');
  if(test > now)
document.getElementById('result').innerHTML = '<p>Still ' + count + ' rehearsals!</p>';

The function dateDtoE converts a date from German format to javascript format, ie. from 13.6.18 to 2018-06-13.

When creating a Date object from the list of dates, the script assumes 10 p.m. as time of day. This is when our rehearsals usually end.

Note the use of a while loop. Lazybones might have used for(i=0;i<dates2go.length;i++), thus recounting the number of elements in the array for every iteration of the loop.

Extra: A solution in Ruby

I know next-to-nothing about ruby, sorry.

require 'time'

def dateDtoE(s)
  h = s.split('.');
  return '20' + h[2] + '-' + h[1] + '-' + h[0]

dates2go = ['28.6.18','5.7.18','12.7.18','19.7.18','26.7.18','2.8.18','9.8.18','30.8.18']
count = 0
now = Time.now()
dates2go.each{ |d|
  h = Time.parse(dateDtoE(d));
  if h > now 
    count += 1
puts "Still #{count} rehearsals."

Note how the loop looks more elegant. Furthermore, ruby’s date parser doesn’t rely on leading zeros.