Answer the question
In order to leave comments, you need to log in
How to calculate shift time in js?
Please help me write a function to calculate shifts.
The starting point is the current date, 00:00 hours, I get it using . Next, the beginning and end of the shift comes from the back in the form (in seconds, can be negative), which must be added to the reference point. Thus, I get the first shift: . In addition, a parameter comes from the back , which indicates how many shifts should be calculated. Changes should be sorted in descending order of dates. Input parameters:moment().startOf('day')
"Start": 25200, "End": 68400
2020-08-07 07:00:00 - 2020-08-07 19:00:00
"Amount"
Текущая дата: 2020-08-07 00:00:00,
Start: 07:00,
End: 19:00,
Amount: 5
2020-08-07 07:00:00 - 2020-08-07 19:00:00
2020-08-06 19:00:00 - 2020-08-07 07:00:00
2020-08-06 07:00:00 - 2020-08-06 19:00:00
2020-08-05 19:00:00 - 2020-08-06 07:00:00
2020-08-05 07:00:00 - 2020-08-05 19:00:00
Answer the question
In order to leave comments, you need to log in
Something like this:
const today = moment().startOf('day');
const dateFormat = 'YYYY-MM-DD HH:mm:ss';
const mapFunc = ({ End, Start, Amount }) => {
const points = [End, Start];
const shift = moment(today).seconds(Start);
const shifts = [];
const order = Start > End;
for (let i = 0; i < Amount; i++) {
shifts.push(
shift.format(dateFormat)
+ ' - '
+ shift
.hours(0) // очищаем часы
.minutes(0) // и минуты
.seconds(points[i % 2]) // чередуем временную точку: чёт - End, нечёт - Start
.add(i % 2 ^ order, 'd') // добавляем день если смена переходит на следующий
.format(dateFormat)
)
}
return shifts
}
console.log(mapFunc({
"Start": 25200,
"End": 68400,
"Amount": 5
}));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question