program story

JavaScript의 날짜 차이

inputbox 2020. 12. 1. 07:59
반응형

JavaScript의 날짜 차이


두 날짜의 차이점을 찾는 방법은 무엇입니까?


Date 객체와 밀리 초 값 을 사용하여 차이를 계산할 수 있습니다.

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.
var d = (b-a); // Difference in milliseconds.

밀리 초를 1000으로 나누어 초로 변환 한 다음 결과를 정수로 변환하여 (정수 / 정수로) 초 수를 얻을 수 있습니다 (이는 밀리 초를 나타내는 소수 부분을 제거함).

var seconds = parseInt((b-a)/1000);

그런 다음 60 minutes으로 나누고 seconds정수로 변환 한 다음 60 hours으로 나누고 minutes정수로 변환 한 다음 동일한 방식으로 더 긴 시간 단위로 전체를 얻을 수 있습니다. 이로부터 하위 단위와 나머지 하위 단위의 값에서 시간 단위의 최대 전체 량을 구하는 함수를 만들 수 있습니다.

function get_whole_values(base_value, time_fractions) {
    time_data = [base_value];
    for (i = 0; i < time_fractions.length; i++) {
        time_data.push(parseInt(time_data[i]/time_fractions[i]));
        time_data[i] = time_data[i] % time_fractions[i];
    }; return time_data;
};
// Input parameters below: base value of 72000 milliseconds, time fractions are
// 1000 (amount of milliseconds in a second) and 60 (amount of seconds in a minute). 
console.log(get_whole_values(72000, [1000, 60]));
// -> [0,12,1] # 0 whole milliseconds, 12 whole seconds, 1 whole minute.

두 번째 Date 객체에 대해 위에 제공된 입력 매개 변수가 무엇인지 궁금하다면 아래 이름을 참조하세요.

new Date(<year>, <month>, <day>, <hours>, <minutes>, <seconds>, <milliseconds>);

이 솔루션의 주석에서 언급했듯이 표시하려는 날짜에 필요한 경우가 아니면 이러한 값을 모두 제공 할 필요가 없습니다.


나는 이것을 발견했고 그것은 나를 위해 잘 작동합니다.

알려진 두 날짜의 차이 계산

안타깝게도 알려진 두 날짜 사이의 일, 주 또는 월과 같은 날짜 간격을 계산하는 것은 Date 개체를 함께 추가 할 수 없기 때문에 쉽지 않습니다. 모든 종류의 계산에서 Date 객체를 사용하려면 먼저 큰 정수로 저장된 Date의 내부 밀리 초 값을 검색해야합니다. 이를 수행하는 함수는 Date.getTime ()입니다. 두 날짜가 모두 변환 된 후 이전 날짜에서 이후 날짜를 빼면 밀리 초 단위의 차이가 반환됩니다. 원하는 간격은 해당 숫자를 해당 밀리 초 수로 나누어 결정할 수 있습니다. 예를 들어, 주어진 밀리 초 수에 대한 일 수를 얻으려면 하루의 밀리 초 수 (1000 x 60 초 x 60 분 x 24 시간) 인 86,400,000으로 나눕니다.

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;

  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));

반올림은 부분 일을 원하는지 여부에 따라 선택 사항입니다.

참고


    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check , is it exceei
    {
    alert( 'date is exceeding one year');
    }

년, 월, 일의 조합으로 표현되는 차이를 찾고 있다면이 함수를 제안합니다.

function interval(date1, date2) {
    if (date1 > date2) { // swap
        var result = interval(date2, date1);
        result.years  = -result.years;
        result.months = -result.months;
        result.days   = -result.days;
        result.hours  = -result.hours;
        return result;
    }
    result = {
        years:  date2.getYear()  - date1.getYear(),
        months: date2.getMonth() - date1.getMonth(),
        days:   date2.getDate()  - date1.getDate(),
        hours:  date2.getHours() - date1.getHours()
    };
    if (result.hours < 0) {
        result.days--;
        result.hours += 24;
    }
    if (result.days < 0) {
        result.months--;
        // days = days left in date1's month, 
        //   plus days that have passed in date2's month
        var copy1 = new Date(date1.getTime());
        copy1.setDate(32);
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();
    }
    if (result.months < 0) {
        result.years--;
        result.months+=12;
    }
    return result;
}

// Be aware that the month argument is zero-based (January = 0)
var date1 = new Date(2015, 4-1, 6);
var date2 = new Date(2015, 5-1, 9);

document.write(JSON.stringify(interval(date1, date2)));

이 솔루션은 윤년 (2 월 29 일)과 월 길이 차이를 우리가 자연스럽게 처리하는 방식 (제 생각에)으로 처리합니다.

예를 들어 2015 년 2 월 28 일과 2015 년 3 월 28 일 사이의 간격은 28 일이 아닌 정확히 한 달로 간주됩니다. 두 날짜가 모두 2016 년이면 차이는 29 일이 아니라 정확히 1 개월입니다.

월과 일이 정확히 같지만 연도가 다른 날짜는 항상 정확한 연도의 차이를 갖습니다. 따라서 2015-03-01과 2016-03-01의 차이는 1 년 1 일이 아니라 정확히 1 년이됩니다 (365 일을 1 년으로 계산하기 때문).


이 답변은 다른 답변 (끝에 링크)을 기반으로 두 날짜의 차이에 관한 것입니다.
간단하기 때문에 작동 방식을 볼 수 있으며, 차이를
시간 단위 (제가 만든 함수) 로 나누고 시간대 문제를 중지하기 위해 UTC로 변환하는 것도 포함됩니다.

function date_units_diff(a, b, unit_amounts) {
    var split_to_whole_units = function (milliseconds, unit_amounts) {
        // unit_amounts = list/array of amounts of milliseconds in a
        // second, seconds in a minute, etc., for example "[1000, 60]".
        time_data = [milliseconds];
        for (i = 0; i < unit_amounts.length; i++) {
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));
            time_data[i] = time_data[i] % unit_amounts[i];
        }; return time_data.reverse();
    }; if (unit_amounts == undefined) {
        unit_amounts = [1000, 60, 60, 24];
    };
    var utc_a = new Date(a.toUTCString());
    var utc_b = new Date(b.toUTCString());
    var diff = (utc_b - utc_a);
    return split_to_whole_units(diff, unit_amounts);
}

// Example of use:
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));

위의 코드 작동 방식

날짜 / 시간 차이 (밀리 초)는 Date 객체를 사용하여 계산할 수 있습니다 .

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.


Date.prototype.addDays = function(days) {

   var dat = new Date(this.valueOf())
   dat.setDate(dat.getDate() + days);
   return dat;
}

function getDates(startDate, stopDate) {

  var dateArray = new Array();
  var currentDate = startDate;
  while (currentDate <= stopDate) {
    dateArray.push(currentDate);
    currentDate = currentDate.addDays(1);
  }
  return dateArray;
}

var dateArray = getDates(new Date(), (new Date().addDays(7)));

for (i = 0; i < dateArray.length; i ++ ) {
  //  alert (dateArray[i]);

    date=('0'+dateArray[i].getDate()).slice(-2);
    month=('0' +(dateArray[i].getMonth()+1)).slice(-2);
    year=dateArray[i].getFullYear();
    alert(date+"-"+month+"-"+year );
}

var DateDiff = function(type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    var returns = -1;

    switch(type){
        case 'm': case 'mm': case 'month': case 'months':
            returns = ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
            break;
        case 'y': case 'yy': case 'year': case 'years':
            returns = years;
            break;
        case 'd': case 'dd': case 'day': case 'days':
            returns = ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
            break;
    }

    return returns;

}

Usage

var qtMonths = DateDiff('mm', new Date('2015-05-05'), new Date());

var qtYears = DateDiff('yy', new Date('2015-05-05'), new Date());

var qtDays = DateDiff('dd', new Date('2015-05-05'), new Date());

OR

var qtMonths = DateDiff('m', new Date('2015-05-05'), new Date()); // m || y || d

var qtMonths = DateDiff('month', new Date('2015-05-05'), new Date()); // month || year || day

var qtMonths = DateDiff('months', new Date('2015-05-05'), new Date()); // months || years || days

...

var DateDiff = function (type, start, end) {

    let // or var
        years = end.getFullYear() - start.getFullYear(),
        monthsStart = start.getMonth(),
        monthsEnd = end.getMonth()
    ;

    if(['m', 'mm', 'month', 'months'].includes(type)/*ES6*/)
        return ( ( ( years * 12 ) - ( 12 - monthsEnd ) ) + ( 12 - monthsStart ) );
    else if(['y', 'yy', 'year', 'years'].includes(type))
        return years;
    else if (['d', 'dd', 'day', 'days'].indexOf(type) !== -1/*EARLIER JAVASCRIPT VERSIONS*/)
        return ( ( end - start ) / ( 1000 * 60 * 60 * 24 ) );
    else
        return -1;

}

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

반응형