JSFiddle - React, Tailwind, and code Playground
by pieterjandc
HTML
<input type="button" onclick="onCheckDate()" value="Check date">
<table id="console"></table>
CSS
html {
margin-bottom: 30px;
}
JavaScript
const seasons = [{
name: 'Spring',
start: new Date(2000, 2, 21),
end: new Date(2000, 5, 20)
},{
name: 'Summer',
start: new Date(2000, 5, 21),
end: new Date(2000, 8, 20)
},{
name: 'Autumn/Fall',
start: new Date(2000, 8, 21),
end: new Date(2000, 11, 20)
},{
name: 'Winter',
start: new Date(2000, 11, 21),
end: new Date(2001, 2, 20)
}];
/** Checks if a date is within a specified season */
function checkSeason(season, date) {
let remappedStart = new Date(2000, season.start.getMonth(), season.start.getDate());
let remappedDate = new Date(2000, date.getMonth(), date.getDate());
let remappedEnd = new Date(2000, season.end.getMonth(), season.end.getDate());
if (season.start.getFullYear() === season.end.getFullYear()) {
return (remappedStart <= remappedDate) && (remappedDate <= remappedEnd);
} else {
return (remappedStart <= remappedDate) && (remappedDate <= new Date(2000, 11, 31))
|| (new Date(2000, 0, 1) <= remappedDate) && (remappedDate <= remappedEnd);
}
}
function findSeason(seasons, date) {
for (let i = 0; i < seasons.length; i++) {
let isInSeason = checkSeason(seasons[i], date);
if (isInSeason === true) {
return seasons[i];
}
}
return null;
}
function appendResult(date, seasonName) {
var tr = document.createElement('tr');
var tdDate = document.createElement('td'); tdDate.innerHTML = date.toLocaleDateString();
var tdSeason = document.createElement('td'); tdSeason.innerHTML = seasonName;
tr.appendChild(tdDate);
tr.appendChild(tdSeason);
document.getElementById('console').appendChild(tr);
}
// Handlers
function onCheckDate() {
let date = new Date(2020, 0, 1);
for (let i = 0; i < 366; i++) {
let season = findSeason(seasons, date);
if (season === null) {
appendResult(date, 'No season');
} else {
appendResult(date, season.name);
}
date.setDate(date.getDate() + 1);
}
}