Skip to content

Instantly share code, notes, and snippets.

@raselupm
Created October 4, 2024 13:33
Show Gist options
  • Save raselupm/132743030a682078abed1b736332ad68 to your computer and use it in GitHub Desktop.
Save raselupm/132743030a682078abed1b736332ad68 to your computer and use it in GitHub Desktop.
date-display.js
function formatDateRange(startDate, endDate) {
const start = new Date(startDate);
const end = new Date(endDate);
const optionsSameYear = { year: 'numeric' };
const optionsSameMonth = { month: 'long', day: 'numeric' };
const optionsFull = { month: 'long', day: 'numeric', year: 'numeric' };
// Check if the start and end dates are the same
if (start.getTime() === end.getTime()) {
return start.toLocaleDateString('en-US', optionsFull);
}
// Check if the start and end dates are in the same month and year
if (start.getMonth() === end.getMonth() && start.getFullYear() === end.getFullYear()) {
return start.toLocaleDateString('en-US', optionsSameMonth) + '-' + end.getDate() + ', ' + start.getFullYear();
}
// Check if the dates are in the same year
if (start.getFullYear() === end.getFullYear()) {
return start.toLocaleDateString('en-US', optionsSameMonth) + ' - ' + end.toLocaleDateString('en-US', optionsSameMonth) + ', ' + start.getFullYear();
}
// Dates are in different months and years
return start.toLocaleDateString('en-US', optionsFull) + ' - ' + end.toLocaleDateString('en-US', optionsFull);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment