Посчитайте количество дней в месяце между двумя датами - PullRequest
0 голосов
/ 07 ноября 2019

У меня есть два типа ввода даты и один тип ввода текста.

Когда я выбираю две даты, я хотел бы знать, сколько дат выбрано за месяц.

Пример:

первая дата: 28.08.2020.

последняя дата: 3.09.2020.

Результат: 4 дня в 08. месяце и 3 дня в 09. месяце

Сейчас у меня есть скрипт, который подсчитывает количестводней между двумя датами

function GetDays() {
  var dropdt = new Date(document.getElementById("dep").value);
  var pickdt = new Date(document.getElementById("arr").value);
  return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}

function cal() {
  if (document.getElementById("dep")) {
    document.getElementById("number-of-dates").value = GetDays();
  }
}
<form action="">
  <input id="arr" type="date" name="arr" onchange="cal()">
  <input id="dep" type="date" name="dep" onchange="cal()">
  <input id="number-of-dates" type="text">
</form>

https://jsfiddle.net/768qrhz3/1/

Ответы [ 4 ]

0 голосов
/ 07 ноября 2019
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const firstDate = new Date(2019, 10, 11);

const secondDate = new Date(2019, 11, 11);

const diffDays = Math.round(Math.abs((firstDate - secondDate) / oneDay));
0 голосов
/ 07 ноября 2019

я думаю, что вы можете попробовать moment.js - это очень приятно обрабатывать дату и время.

https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/07-difference/

    var a = moment([2007, 0, 29]);
    var b = moment([2007, 0, 28]);
    a.diff(b, 'days') // 1
0 голосов
/ 07 ноября 2019

Как то так? Вы получаете дни в месяце даже для високосных лет, как февраль 2020 года.

function getDays() {
    var dropdt = new Date(document.getElementById("arr").value);
    var pickdt = new Date(document.getElementById("dep").value);
    var result = "";
    for (var year = dropdt.getFullYear(); year <= pickdt.getFullYear(); year++) {
        var firstMonth = (year == dropdt.getFullYear()) ? dropdt.getMonth() : 0;
        var lastMonth = (year == pickdt.getFullYear()) ? pickdt.getMonth() : 11;
        for (var month = firstMonth; month <= lastMonth; month++) {
            var firstDay = (year === dropdt.getFullYear() && month === firstMonth) ? dropdt.getDate() : 1;
            var lastDay = (year === pickdt.getFullYear() && month === lastMonth) ? pickdt.getDate() : 0;
            var lastDateMonth = (lastDay === 0) ? (month + 1) : month
            var firstDate = new Date(year, month, firstDay);
            var lastDate = new Date(year, lastDateMonth, lastDay);
            result += (month + 1) + " - " + parseInt((lastDate - firstDate) / (24 * 3600 * 1000) + 1) + "; ";
        }
    }
    return result;
}

function cal() {
    if (document.getElementById("dep")) {
        document.getElementById("number-of-dates").value = getDays();
    }
}
<form action="javascript:void(0);">
  <input id="arr" type="date" name="arr" value="2019-09-15"> 
  <input id="dep" type="date" name="dep" value="2020-03-15">
  <button onclick="cal()">Calculate</button>
  <input style="width:400px" id="number-of-dates" type="text">
</form>
0 голосов
/ 07 ноября 2019

Можете ли вы попробовать приведенный ниже код.

var a = '28.09.2020';
var b = '03.10.2020';

var calculateNumberOfDaysPerMonthAndYear = function(a, b) {
    function compareDatesOnBasedOfMonthAndYear(a, b) {
        if (b[2] > a[2]) return 1;
        if (b[2] < a[2]) return -1;

        if (b[1] > a[1]) return 1;
        if (b[1] < a[1]) return -1;
        return 0;
    }

    function getNextMonth(a) {
        var nextMonth = [ ...a ];
        nextMonth[1] += 1;
        if (nextMonth[1] === 13) {
            nextMonth[1] = 1;
            nextMonth[2] += 1;
        }

        return nextMonth;
    }

    var finalJson = {};
    var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

    var splittedDateA = a.split('.').map(d => parseInt(d));
    var splittedDateB = b.split('.').map(d => parseInt(d));

    var key = splittedDateA[1] + '.' + splittedDateA[2];
    finalJson[key] = daysInMonth[splittedDateA[1] - 1] + 1 - splittedDateA[0];
    if (splittedDateA[2] % 4 === 0) finalJson[key] += 1;

    var currentDate = getNextMonth(splittedDateA);
    while(compareDatesOnBasedOfMonthAndYear(currentDate, splittedDateB)) {
        key = currentDate[1] + '.' + currentDate[2];
        finalJson[key] = daysInMonth[currentDate[1] - 1];
        currentDate = getNextMonth(currentDate);
    }

    key = splittedDateB[1] + '.' + splittedDateB[2];
    finalJson[key] = splittedDateB[0];

    return finalJson;
};

console.log(calculateNumberOfDaysPerMonthAndYear(a, b));

Выходными данными будет объект JSON с ключом в виде комбинации месяца и года (например, 8.2020), а значением будет количество дней.

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...