Skip to content

Instantly share code, notes, and snippets.

@CarsonSlovoka
Created September 28, 2023 04:11
Show Gist options
  • Save CarsonSlovoka/a5b54f8863945fa2c8c4fb36cb7330a9 to your computer and use it in GitHub Desktop.
Save CarsonSlovoka/a5b54f8863945fa2c8c4fb36cb7330a9 to your computer and use it in GitHub Desktop.
給定一個元素都為yyyy/mm/dd的array,將其連續的日期使用`${start}-{end}`的方式串在一起
<script>
function formatDateRange(dateArray) {
if (dateArray.length < 2) {
return dateArray
}
const result = dateArray.reduce((acc, curDateStr, index, array) => {
const curDate = new Date(curDateStr)
if (acc.rangeEnd && curDate === acc.rangeEnd) {
return acc
}
if (index+1 <= array.length) {
const nextDate = new Date(array[index+1])
const endDate = curDate.setDate(curDate.getDate()+1)
if (endDate - nextDate === 0) {
// 連續
if (acc.rangeStart === null) {
acc.rangeStart = curDateStr
}
acc.rangeEnd = array[index+1]
return acc
}
}
// 不連續
if (acc.rangeEnd !== null) {
// 放入之前連續時的資料
acc.formatted.push(`${acc.rangeStart}-${acc.rangeEnd}`)
acc.rangeStart = null
acc.rangeEnd = null
} else {
acc.formatted.push(curDateStr)
}
return acc;
}, {
rangeStart: null,
rangeEnd: null,
formatted: []
})
return result.formatted
}
for (const testData of [
['2023/09/01'],
[
'2023/09/01',
'2023/09/08',
'2023/09/02',
'2023/09/12',
'2023/09/03',
'2023/09/04',
],
[
'2023/09/30',
'2023/10/1',
'2023/10/5',
'2023/10/2',
'2023/10/6',
'2023/12/31',
'2024/1/1',
'2024/1/5',
'2024/1/2',
],
]){
testData.sort((b, a)=>{
const dateA = new Date(a)
const dateB = new Date(b)
return dateB - dateA
})
const formattedArray = formatDateRange(testData)
console.log(formattedArray)
}
/*
Output:
['2023/09/01']
['2023/09/01-2023/09/04', '2023/09/08', '2023/09/12']
['2023/09/30-2023/10/2', '2023/10/5-2023/10/6', '2023/12/31-2024/1/2', '2024/1/5']
**/
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment