First, here's the documentation on the Javascript Date object and its prototype.
So, how can you determine if a particular day (date2
) is one day after another (date1
)? Well, add one day to date1
and see if the dates match:
var date1_tomorrow = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate() + 1);
if (date1_tomorrow.getFullYear() == date2.getFullYear() && date1_tomorrow.getMonth() == date2.getMonth() && date1_tomorrow.getDate() == date2.getDate()) {
return "tomorrow"; // date2 is one day after date1.
}
If you want to determine if date2
is two days after date1
, you can use the same logic as above but add 2 days instead of 1:
var date1_overmorrow = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate() + 2);
if (date1_overmorrow.getFullYear() == date2.getFullYear() && date1_overmorrow.getMonth() == date2.getMonth() && date1_overmorrow.getDate() == date2.getDate()) {
return "the day after tomorrow"; // date2 is two days after date1.
}
If the dates are not 1 or 2 days apart, the final bit would be to just return the date in your desired format:
return date2.toLocaleString(); // Firefox 29+, Chrome 24+, IE 11+
// OR
return date2.getFullYear() + '/' + (date2.getMonth() + 1) + '/' + date2.getDate() + ' ' + date2.getHours() + ':' + date2.getMinutes() + ':' + date2.getSeconds(); // Et al.
Test
function incrementDate(date, n) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + n);
}
function compareDates(date1, date2) {
return date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate();
}
function formatDate(date) {
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
}
$(function() {
var $output = $('#output');
var comparisons = [
{'start': new Date(2016, 6 - 1, 1), 'inc': 1, 'target': new Date(2016, 6 - 1, 2)},
{'start': new Date(2016, 6 - 1, 30), 'inc': 1, 'target': new Date(2016, 7 - 1, 1)},
{'start': new Date(2016, 12 - 1, 31), 'inc': 1, 'target': new Date(2017, 1 - 1, 1)}
];
for (var i = 0, len = comparisons.length; i < len; i += 1) {
var comp = comparisons[i];
var $row = $('<tr>');
$('<td>').text(formatDate(comp.start)).appendTo($row);
$('<td>').text(comp.inc).appendTo($row);
$('<td>').text(formatDate(comp.target)).appendTo($row);
$('<td>').text(compareDates(comp.target, incrementDate(comp.start, comp.inc)) ? 'yes' : 'no').appendTo($row);
$output.append($row);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Start</th>
<th>Inc</th>
<th>Target</th>
<th>Equal</th>
</tr>
</thead>
<tbody id="output">
</tbody>
</table>