Skip to content

Instantly share code, notes, and snippets.

@qertis qertis/fillRangeTimes.js
Last active Mar 8, 2017

Embed
What would you like to do?
Функция заполнения датами пустотых дат
/**
* Например если есть "2016-05-01" и "2016-05-03" то автоматически создаются
* ["2016-05-01", "2016-05-02", "2016-05-03"]
*
* @desc Эта функция заполняет датами пустоты во времени
* @param from {String|Date}
* @param until {String|Date}
* @return {Array}
* @link https://gist.github.com/qertis/c1ed54a5f7cbaa9709030c0ff14d5b9e
* @example fillRangeTimes('2015-01-01', "2016-03-02");
*/
function fillRangeTimes(from, until) {
function getDifferenceDays(fromDate, untilDate) {
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
const differenceDays = Math.floor((untilDate - fromDate) / (_MS_PER_DAY));
if (differenceDays < 0) {
throw new Error('until less from');
}
return differenceDays;
}
function isDate() {
return (from instanceof Date || typeof from === 'string') &&
(until instanceof Date || typeof until === 'string');
}
if (!isDate()) {
throw new Error('unknown param type');
}
const result = [];
const fromDate = new Date(from);
const untilDate = new Date(until);
const dayOffLength = getDifferenceDays(fromDate, untilDate);
for (let i = 0; i < dayOffLength; i++) {
const date = new Date(fromDate);
date.setDate(fromDate.getDate() + i);
fromDate.setHours(0);
fromDate.setMinutes(0);
fromDate.setMinutes(0);
result.push(date);
}
result.push(untilDate);
return result;
}
@qertis

This comment has been minimized.

Copy link
Owner Author

qertis commented May 15, 2016

//test
fillRangeTimes('2015-01-01', '2016-03-02');
//test end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.