Date parsing
by James Long
HTML
<ol>
<li><span class="date">18/11/2015</span></li>
<li><span class="date">02/12/2015</span></li>
<li><span class="date js-today"></span></li>
<li><span class="date">30/12/2025</span></li>
<li><span class="date">13/01/2026</span></li>
</ol>
CSS
.past { background-color: #F66; } /* red */
.present { background-color: #6F6; } /* green */
.future { background-color: #66F; } /* blue */
JavaScript
// A little hack to ensure that one of the entries is always today.
document.addEventListener('DOMContentLoaded', function () {
var today = new Date();
var todayString = today.getDate() + '/' + (today.getMonth() + 1) + '/' + today.getFullYear();
document.querySelector('.js-today').textContent = todayString;
});
document.addEventListener('DOMContentLoaded', function () {
'use strict';
// You can just write
// var day = 86400000
// but I find that spelling it out like this is easier to understand.
var day = 1000 * 60 * 60 * 24;
function dmyToDate(dmy) {
var parts = dmy.split('/');
parts[1] -= 1; // Months are 0-indexed
return new Date(parts[2], parts[1], parts[0]);
}
function numberToNearest(number, nearest, method) {
var prop = 'round';
if (typeof method === 'string' && typeof Math[method] === 'function') {
prop = method;
}
return Math[prop](number / nearest) * nearest;
}
function getDayStart(date) {
if (typeof date !== 'number' || !(date instanceof Date)) {
date = Date.now();
}
return numberToNearest(+date, day, 'floor');
}
var today = getDayStart();
var cnd = document.getElementsByClassName('date');
var i = 0;
var il = cnd.length;
var cndElem;
var cndDate;
while (i < il) {
cndElem = cnd[i];
cndDate = dmyToDate(cndElem.textContent);
if (cndDate < today) {
cndElem.className += ' past';
} else if (cndDate > today) {
cndElem.className += ' future';
} else {
cndElem.className += ' present';
}
i += 1;
}
});