jQuery date and time alterations
Plus and minus 1 unit of granularity for each time
by Andy Jones
HTML
<h3>jQuery date and time alterations</h3>
<p>Plus and minus 1 unit of granularity for each time</p>
<table>
<thead>
<tr>
<th>Date/Time change</th>
<th>Minus</th>
<th>Current</th>
<th>Plus</th>
</tr>
</thead>
<tbody id="timeOutput">
</tbody>
</table>
CSS
table {
border-collapse: collapse;
}
tbody tr td {
border-bottom:1px solid #ccc;
}
JavaScript
//retrieve the current time
function getCurrentDate() {
var currentDate = new Date();
return new Date(currentDate);
}
//get the increasedecrease in date/time value
function getTimeDifference(dateRange) {
var now = getCurrentDate();
var dateObject = new Date();
var min = dateObject;
var max = dateObject;
switch (dateRange) {
case 'Yearly':
min.setFullYear(now.getFullYear() - 1);
max.setFullYear(now.getFullYear() + 1);
break;
case 'Monthly':
min.setMonth(now.getMonth() - 1);
max.setMonth(now.getMonth() + 1);
break;
case 'Weekly':
min.setDate(now.getDate() - 7);
max.setDate(now.getDate() + 7);
break;
case 'Daily':
min.setDate(now.getDate() - 1);
max.setDate(now.getDate() + 1);
break;
case 'Hourly':
min.setHours(now.getHours() - 1);
max.setHours(now.getHours() + 1);
break;
case 'Minutes':
min.setMinutes(now.getMinutes() - 1);
max.setMinutes(now.getMinutes() + 1);
break;
}
return { min: min, max: max };
};
//render the output to the table
var tableBody = $('#timeOutput');
tableBody.append('<tr><td>Year</td><td>' + getTimeDifference('Yearly').min + '</td><td>' + getCurrentDate() + '</td><td>' + getTimeDifference('Yearly').max + '</td></tr>');
tableBody.append('<tr><td>Month</td><td>' + getTimeDifference('Monthly').min + '</td><td>' + getCurrentDate() + '</td><td>' + getTimeDifference('Monthly').max + '</td></tr>');
tableBody.append('<tr><td>Week</td><td>' + getTimeDifference('Weekly').min + '</td><td>' + getCurrentDate() + '</td><td>' + getTimeDifference('Weekly').max + '</td></tr>');
tableBody.append('<tr><td>Day</td><td>' + getTimeDifference('Daily').min + '</td><td>' + getCurrentDate() + '</td><td>' + getTimeDifference('Daily').max +...