IT박스

JavaScript에서 두 날짜의 월 차이

itboxs 2020. 7. 16. 19:46
반응형

JavaScript에서 두 날짜의 월 차이


JavaScript에서 두 Date () 객체의 차이를 어떻게 해결하고 차이의 개월 수 만 반환합니까?

어떤 도움이라도 좋을 것입니다 :)


"차이의 개월 수"에 대한 정의는 많은 해석이 필요합니다. :-)

JavaScript 날짜 객체에서 년, 월 및 일을 얻을 수 있습니다. 찾고있는 정보에 따라 두 시점 사이에 몇 개월이 있는지 파악할 수 있습니다.

예를 들어, 커프스 밖에서 사이에 몇 달의 전체 월이 몇 달 인지 계산하지 않습니다 (예 : 각 날짜가있는 월 제외).

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 15: December 2008, all of 2009, and Jan & Feb 2010

monthDiff(
    new Date(2010, 0, 1),  // January 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 1: February 2010 is the only full month between them

monthDiff(
    new Date(2010, 1, 1),  // February 1st, 2010
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 0: There are no *full* months between them

JavaScript의 월 값은 0 = 1 월로 시작합니다.

전형적인 2 월의 3 일은 8 월의 3 일 (~ 9.677 %)보다 3 월 (~ 10.714 %)의 큰 비율이며, 물론 2 월도 움직이는 목표이기 때문에 위의 분수를 포함하는 것은 훨씬 더 복잡합니다. 윤년인지에 따라.

JavaScript에 사용할 수있는 일부 날짜 및 시간 라이브러리 도 있으므로 이러한 종류의 작업을 쉽게 수행 할 수 있습니다.


월의 날짜를 고려하지 않으면 훨씬 간단한 솔루션입니다.

function monthDiff(dateFrom, dateTo) {
 return dateTo.getMonth() - dateFrom.getMonth() + 
   (12 * (dateTo.getFullYear() - dateFrom.getFullYear()))
}


//examples
console.log(monthDiff(new Date(2000, 01), new Date(2000, 02))) // 1
console.log(monthDiff(new Date(1999, 02), new Date(2000, 02))) // 12 full year
console.log(monthDiff(new Date(2009, 11), new Date(2010, 0))) // 1

월 인덱스는 0부터 시작합니다. 이것은 January = 0및을 의미합니다 December = 11.


때로는 하루 부분을 완전히 무시하고 두 날짜 사이의 월 수량 만 가져오고 싶을 수도 있습니다. 예를 들어, 2013/06/21 및 2013/10/18의 두 날짜가 있고 2013/06 및 2013/10 부분에만 관심이 있다면 시나리오와 가능한 솔루션은 다음과 같습니다.

var date1=new Date(2013,5,21);//Remember, months are 0 based in JS
var date2=new Date(2013,9,18);
var year1=date1.getFullYear();
var year2=date2.getFullYear();
var month1=date1.getMonth();
var month2=date2.getMonth();
if(month1===0){ //Have to take into account
  month1++;
  month2++;
}
var numberOfMonths; 

1. month1과 month2를 제외한 두 날짜 사이의 월 수만 원하는 경우

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) - 1;

2. 달 중 하나를 포함하려면

numberOfMonths = (year2 - year1) * 12 + (month2 - month1);

3. 두 달을 모두 포함하려면

numberOfMonths = (year2 - year1) * 12 + (month2 - month1) + 1;

다음은 두 날짜 사이의 월 수를 정확하게 제공하는 함수입니다.
기본 동작은 전체 개월 만 계산합니다. 예를 들어 3 개월과 1 일은 3 개월의 차이를 가져옵니다. roundUpFractionalMonthsparam을로 설정하면이를 방지 할 수 true있으므로 3 개월과 1 일 차이는 4 개월로 반환됩니다.

위의 허용 된 답변 (TJ Crowder 's answer)은 정확하지 않으며 때로는 잘못된 값을 반환합니다.

예를 들어, 분명히 잘못된 것을 monthDiff(new Date('Jul 01, 2015'), new Date('Aug 05, 2015'))반환합니다 0. 정확한 차이는 1 개월 또는 2 개월입니다.

내가 쓴 기능은 다음과 같습니다.

function getMonthsBetween(date1,date2,roundUpFractionalMonths)
{
    //Months will be calculated between start and end dates.
    //Make sure start date is less than end date.
    //But remember if the difference should be negative.
    var startDate=date1;
    var endDate=date2;
    var inverse=false;
    if(date1>date2)
    {
        startDate=date2;
        endDate=date1;
        inverse=true;
    }

    //Calculate the differences between the start and end dates
    var yearsDifference=endDate.getFullYear()-startDate.getFullYear();
    var monthsDifference=endDate.getMonth()-startDate.getMonth();
    var daysDifference=endDate.getDate()-startDate.getDate();

    var monthCorrection=0;
    //If roundUpFractionalMonths is true, check if an extra month needs to be added from rounding up.
    //The difference is done by ceiling (round up), e.g. 3 months and 1 day will be 4 months.
    if(roundUpFractionalMonths===true && daysDifference>0)
    {
        monthCorrection=1;
    }
    //If the day difference between the 2 months is negative, the last month is not a whole month.
    else if(roundUpFractionalMonths!==true && daysDifference<0)
    {
        monthCorrection=-1;
    }

    return (inverse?-1:1)*(yearsDifference*12+monthsDifference+monthCorrection);
};

28, 29, 30 또는 31 일인 달에 관계없이 전체 월을 계산해야하는 경우 아래가 작동합니다.

var months = to.getMonth() - from.getMonth() 
    + (12 * (to.getFullYear() - from.getFullYear()));

if(to.getDate() < from.getDate()){
    months--;
}
return months;

이 답변은 확장 버전으로 https://stackoverflow.com/a/4312956/1987208 이지만 1 월 31 일에서 2 월 1 일 (1 일)까지 1 개월로 계산되는 경우를 수정합니다.

이것은 다음을 다룰 것이다;

  • 1 월 1 일 ~ 1 월 31 일 ---> 30 일 --->은 0이됩니다 (1 개월이 아니기 때문에 논리적 임).
  • 2 월 1 일 ~ 3 월 1 일 ---> 28 또는 29 일 ---> 1 (결과는 1 개월이므로 논리)
  • 2 월 15 일 ~ 3 월 15 일 ---> 28 또는 29 일 ---> 1 (결과는 한 달이 지났으므로 논리)
  • 1 월 31 일 ~ 2 월 1 일 ---> 1 일 ---> 결과는 0입니다 (분명하지만 1 개월 후 게시물에 언급 된 답변).

JavaScript에서 두 날짜의 월 차이 :

 start_date = new Date(year, month, day); //Create start date object by passing appropiate argument
 end_date = new Date(new Date(year, month, day)

start_date와 end_date 사이의 총 개월 :

 total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth())

나는 이것이 정말로 늦다는 것을 알고 있지만 어쨌든 다른 사람들을 돕기 위해 게시하는 것입니다. 다음은 두 날짜 사이의 월 차이를 계산하는 데 도움이되는 기능입니다. 그것은 Mr.Crowder 's에 비해 상당히 야만적이지만 날짜 개체를 단계별로 수행하여보다 정확한 결과를 제공합니다. 그것은 AS3에 있지만 강력한 타이핑을 버릴 수 있어야하며 JS가 있습니다. 누군가를 더 멋지게 바라 보게 해주세요!

    function countMonths ( startDate:Date, endDate:Date ):int
    {
        var stepDate:Date = new Date;
        stepDate.time = startDate.time;
        var monthCount:int;

        while( stepDate.time <= endDate.time ) { 
            stepDate.month += 1;
            monthCount += 1;
        }           

        if ( stepDate != endDate ) { 
            monthCount -= 1;
        }

        return monthCount;
    }

각 날짜를 월 단위로 고려한 다음 빼서 차이를 찾으십시오.

var past_date = new Date('11/1/2014');
var current_date = new Date();

var difference = (current_date.getFullYear()*12 + current_date.getMonth()) - (past_date.getFullYear()*12 + past_date.getMonth());

이렇게하면 날짜를 무시하고 두 날짜 사이의 월 차이를 얻을 수 있습니다.


@TJ의 대답을 확장하기 위해 달력 개월이 아닌 간단한 달을 찾고 있다면 d2의 날짜가 d1보다 크거나 같은지 확인할 수 있습니다. 즉, d2가 해당 달에 비해 d2가 그 달에 늦으면 1 개월이 더 있습니다. 그래서 당신은 이것을 할 수 있어야합니다 :

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth() + 1;
    months += d2.getMonth();
    // edit: increment months if d2 comes later in its month than d1 in its month
    if (d2.getDate() >= d1.getDate())
        months++
    // end edit
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2008, 10, 4), // November 4th, 2008
    new Date(2010, 2, 12)  // March 12th, 2010
);
// Result: 16; 4 Nov – 4 Dec '08, 4 Dec '08 – 4 Dec '09, 4 Dec '09 – 4 March '10

이는 시간 문제 (예 : 3 월 3 일 오후 4시 4시 및 4 월 3 일 오후 3시)를 완전히 설명하지는 않지만보다 정확하고 몇 줄의 코드 만 있으면됩니다.


수학 및 빠른 두 가지 접근 방식이 있지만 달력의 변동성 또는 반복적 및 느린 방식이 있지만 모든 이상을 처리합니다 (적어도 테스트를 거친 라이브러리에 처리하는 델리게이트).

캘린더를 반복하면 시작 날짜가 1 개월 씩 증가하고 종료 날짜가 지 났는지 확인합니다. 이 대표는 내장 된 날짜 () 클래스에 이상 처리하지만, 느린 될 수 있습니다 경우 당신이 날짜의 많은 수의이 일을하고 있습니다. 제임스의 대답은이 방법을 사용합니다. 아이디어를 싫어하는만큼 이것이 "가장 안전한"접근 방식이라고 생각합니다. 하나의 계산 만 수행하는 경우 성능 차이는 무시할 수 있습니다. 우리는 한 번만 수행되는 작업을 과도하게 최적화하려는 경향이 있습니다.

이제 데이터 집합에서이 함수를 계산하는 경우 각 행에서 해당 함수를 실행하지 않으려 고 할 수도 있습니다 (또는 레코드 당 여러 번 금지). 이 경우, 당신은 여기에 다른 답변의 거의 모든 사용할 수 있습니다 제외 (차이 사이에 단지 잘못 허용 대답, new Date()그리고 new Date()-1)?

다음은 달 길이와 윤년이 다른 수학 및 빠른 접근 방식에 대한 설명입니다. 이것을 데이터 세트에 적용 할 경우 (이 계산을 반복해서 수행하는 경우) 이와 같은 함수 만 사용해야합니다. 한 번만 수행 해야하는 경우 Date () 객체에 대한 모든 (많은) 예외 처리를 위임하는 위의 James 반복 접근 방식을 사용하십시오.

function diffInMonths(from, to){
    var months = to.getMonth() - from.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));

    if(to.getDate() < from.getDate()){
        var newFrom = new Date(to.getFullYear(),to.getMonth(),from.getDate());
        if (to < newFrom  && to.getMonth() == newFrom.getMonth() && to.getYear() %4 != 0){
            months--;
        }
    }

    return months;
}

여기에서 당신은 더 적은 루프와 다른 접근 방식을 이동 :

calculateTotalMonthsDifference = function(firstDate, secondDate) {
        var fm = firstDate.getMonth();
        var fy = firstDate.getFullYear();
        var sm = secondDate.getMonth();
        var sy = secondDate.getFullYear();
        var months = Math.abs(((fy - sy) * 12) + fm - sm);
        var firstBefore = firstDate > secondDate;
        firstDate.setFullYear(sy);
        firstDate.setMonth(sm);
        firstBefore ? firstDate < secondDate ? months-- : "" : secondDate < firstDate ? months-- : "";
        return months;
}

두 날짜 사이의 차이는 월의 일부 (일)를 포함하여 계산합니다.


var difference = (date2.getDate() - date1.getDate()) / 30 +
    date2.getMonth() - date1.getMonth() +
    (12 * (date2.getFullYear() - date1.getFullYear()));

예 :
date1 : 24/09/2015 (2015 년 9 월 24 일)
date2 : 09/11/2015 (2015 년 11 월 9 일)
차이 : 2.5 (개월)


이것은 잘 작동합니다 :

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months += d2.getMonth() - d1.getMonth();
    return months;
}

이 솔루션을 고려할 수도 있습니다. function이는 월차를 정수 또는 숫자로 반환합니다.

시작 날짜 를 첫 번째 또는 마지막으로 전달하면 param내결함성이 있습니다. 즉, 함수는 여전히 동일한 값을 반환합니다.

const diffInMonths = (end, start) => {
   var timeDiff = Math.abs(end.getTime() - start.getTime());
   return Math.round(timeDiff / (2e3 * 3600 * 365.25));
}

const result = diffInMonths(new Date(2015, 3, 28), new Date(2010, 1, 25));

// shows month difference as integer/number
console.log(result);


function calcualteMonthYr(){
    var fromDate =new Date($('#txtDurationFrom2').val()); //date picker (text fields)
    var toDate = new Date($('#txtDurationTo2').val());

var months=0;
        months = (toDate.getFullYear() - fromDate.getFullYear()) * 12;
        months -= fromDate.getMonth();
        months += toDate.getMonth();
            if (toDate.getDate() < fromDate.getDate()){
                months--;
            }
    $('#txtTimePeriod2').val(months);
}

다음 코드는 부분 월의 nr 일을 고려하여 두 날짜 사이의 전체 월을 반환합니다.

var monthDiff = function(d1, d2) {
  if( d2 < d1 ) { 
    var dTmp = d2;
    d2 = d1;
    d1 = dTmp;
  }

  var months = (d2.getFullYear() - d1.getFullYear()) * 12;
  months -= d1.getMonth() + 1;
  months += d2.getMonth();

  if( d1.getDate() <= d2.getDate() ) months += 1;

  return months;
}

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 20))
> 1

monthDiff(new Date(2015, 01, 20), new Date(2015, 02, 19))
> 0

monthDiff(new Date(2015, 01, 20), new Date(2015, 01, 22))
> 0

function monthDiff(d1, d2) {
var months, d1day, d2day, d1new, d2new, diffdate,d2month,d2year,d1maxday,d2maxday;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
months = (months <= 0 ? 0 : months);
d1day = d1.getDate();
d2day = d2.getDate();
if(d1day > d2day)
{
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d1new = new Date(d2year, d2month-1, d1day,0,0,0,0);
    var timeDiff = Math.abs(d2.getTime() - d1new.getTime());
          diffdate = Math.abs(Math.ceil(timeDiff / (1000 * 3600 * 24))); 
    d1new = new Date(d2year, d2month, 1,0,0,0,0);
    d1new.setDate(d1new.getDate()-1);
    d1maxday = d1new.getDate();
    months += diffdate / d1maxday;
}
else
{
      if(!(d1.getMonth() == d2.getMonth() && d1.getFullYear() == d2.getFullYear()))
    {
        months += 1;
    }
    diffdate = d2day - d1day + 1;
    d2month = d2.getMonth();
    d2year = d2.getFullYear();
    d2new = new Date(d2year, d2month + 1, 1, 0, 0, 0, 0);
    d2new.setDate(d2new.getDate()-1);
    d2maxday = d2new.getDate();
    months += diffdate / d2maxday;
}

return months;

}


아래의 논리는 달의 차이를 가져올 것입니다

(endDate.getFullYear()*12+endDate.getMonth())-(startDate.getFullYear()*12+startDate.getMonth())

function monthDiff(date1, date2, countDays) {

  countDays = (typeof countDays !== 'undefined') ?  countDays : false;

  if (!date1 || !date2) {
    return 0;
  }

  let bigDate = date1;
  let smallDate = date2;

  if (date1 < date2) {
    bigDate = date2;
    smallDate = date1;
  }

  let monthsCount = (bigDate.getFullYear() - smallDate.getFullYear()) * 12 + (bigDate.getMonth() - smallDate.getMonth());

  if (countDays && bigDate.getDate() < smallDate.getDate()) {
    --monthsCount;
  }

  return monthsCount;
}

내가 사용하는 것을보십시오 :

function monthDiff() {
    var startdate = Date.parseExact($("#startingDate").val(), "dd/MM/yyyy");
    var enddate = Date.parseExact($("#endingDate").val(), "dd/MM/yyyy");
    var months = 0;
    while (startdate < enddate) {
        if (startdate.getMonth() === 1 && startdate.getDate() === 28) {
            months++;
            startdate.addMonths(1);
            startdate.addDays(2);
        } else {
            months++;
            startdate.addMonths(1);
        }
    }
    return months;
}

또한 일 수를 세고 몇 개월 단위로 변환합니다.

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;   //calculates months between two years
    months -= d1.getMonth() + 1; 
    months += d2.getMonth();  //calculates number of complete months between two months
    day1 = 30-d1.getDate();  
    day2 = day1 + d2.getDate();
    months += parseInt(day2/30);  //calculates no of complete months lie between two dates
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2017, 8, 8), // Aug 8th, 2017    (d1)
    new Date(2017, 12, 12)  // Dec 12th, 2017   (d2)
);
//return value will be 4 months 

번영을 위해

With Moment.js you can achieve this by doing:

const monthsLeft = moment(endDate).diff(moment(startDate), 'month');

anyVar = (((DisplayTo.getFullYear() * 12) + DisplayTo.getMonth()) - ((DisplayFrom.getFullYear() * 12) + DisplayFrom.getMonth()));

One approach would be to write a simple Java Web Service (REST/JSON) that uses JODA library

http://joda-time.sourceforge.net/faq.html#datediff

to calculate difference between two dates and call that service from javascript.

This assumes your back end is in Java.

참고URL : https://stackoverflow.com/questions/2536379/difference-in-months-between-two-dates-in-javascript

반응형