I have an array of dates:
dates:
[ { start: '30.05.2022 02:30:00', end: '30.05.2022 03:30:00' }
, { start: '30.05.2022 02:34:01', end: '3.06.2022 04:34:01' }
]
What I want is to make the start of the second item of an array to be the end of the first item of an array and without breaking duration. The desired result should look like this:
dates:
[ { start: '30.05.2022 02:30:00', end: '30.05.2022 03:30:00' }
, { start: '30.05.2022 03:30:00', end: '3.06.2022 05:30:00' }
]
I've tried to implement my solution, but it gives incorrect result, because duration of momentjs exceeds 24 hours:
const dateFormat = 'DD.MM.YYYY HH:mm:ss'
const parseDateByMoment= (dateString) => {
return moment(dateString, dateFormat)
}
const convertDateToString= (dateString) => {
return dateString.format(dateFormat)
}
const addOrSubtractDate = (startDate, endDate, isAdding) => {
const startDateDuration = moment.duration(startDate.format("HH:mm:ss"))
const endDateDuration = moment.duration(endDate.format("HH:mm:ss"))
const result = isAdding
? endDateDuration + startDateDuration
: endDateDuration - startDateDuration
return moment.duration(result)
}
const formatToTime = (diff) => {
return moment.utc(diff).format("HH:mm:ss.SSS");
}
const makeSequentialTimeInTracks = (dates) => {
dates.forEach((aDate, index) => {
if (index !== 0) {
let prevEndDate = dates[index - 1].end
prevEndDate = parseDateByMoment(prevEndDate)
aDate.start = convertDateToString(prevEndDate)
// console.log('aDate.start is', aDate.start)
const start = parseDateByMoment(aDate.start)
const durationStart = moment.duration(start.format("HH:mm:ss"))
console.log('2. aDate.start is', start)
let end = parseDateByMoment(aDate.end)
const durationEnd = moment.duration(end.format("HH:mm:ss"))
console.log('2. aDate.end is', end)
let difference = addOrSubtractDate(start, end, false)
difference = moment(difference)
let durationDifference = moment.duration(difference.format("HH:mm:ss"))
console.log('durationDifference',
moment.duration(durationDifference))
const temp = start.clone()
console.log('2. temp is', temp)
temp.startOf('day').add(difference)
console.log('temp', temp.format(dateFormat))
// aDate.end = convertDateToString(addOrSubtractDate(start, difference, true))
}
});
return dates
}
const sequantialTime = makeSequentialTime(dates)
console.log(dates)
Any soultion with pure JavaScript or momentjs library will be highly appreciated.
without breaking durationeven if the last duration go on the next day ?