Created
October 4, 2024 13:33
-
-
Save raselupm/132743030a682078abed1b736332ad68 to your computer and use it in GitHub Desktop.
date-display.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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