Programing

JavaScript로 한 달의 일수를 결정하는 가장 좋은 방법은 무엇입니까?

lottogame 2020. 8. 26. 08:21
반응형

JavaScript로 한 달의 일수를 결정하는 가장 좋은 방법은 무엇입니까?


이 기능을 사용해 왔지만 가장 효율적이고 정확한 방법이 무엇인지 알고 싶습니다.

function daysInMonth(iMonth, iYear) {
   return 32 - new Date(iYear, iMonth, 32).getDate();
}

function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.
  return new Date(year, month, 0).getDate();
}

console.log(daysInMonth(2, 1999)); // February in a non-leap year.
console.log(daysInMonth(2, 2000)); // February in a leap year.

0 일은 이전 달의 마지막 날입니다. 월 생성자는 0부터 시작하므로 잘 작동합니다. 약간의 해킹이지만 기본적으로 32를 빼서 수행하는 작업입니다.


이 함수를 자주 호출하면 성능 향상을 위해 값을 캐시하는 것이 유용 할 수 있습니다.

다음은 FlySwat의 답변 캐싱 버전입니다 .

var daysInMonth = (function() {
    var cache = {};
    return function(month, year) {
        var entry = year + '-' + month;

        if (cache[entry]) return cache[entry];

        return cache[entry] = new Date(year, month, 0).getDate();
    }
})();

일부 답변 (다른 질문에서도)은 윤년 문제가 있거나 Date-object를 사용했습니다. 자바 스크립트가 Date object1970 년 1 월 1 일 양측에서 약 285616 년 (100,000,000 일)을 다루지 만, 저는 여러 브라우저 (특히 0 ~ 99 년) 에서 모든 종류의 예기치 않은 날짜 불일치에 지쳤습니다 . 계산 방법도 궁금했습니다.

그래서 나는 정확한 계산을 위해 간단하고 무엇보다 작은 알고리즘을 작성했습니다 ( Proleptic Gregorian / Astronomical / ISO 8601 : 2004 (절 4.3.2.1), 그래서 이 존재하고 윤년이고 음의 년이 지원됩니다 ). 주어진 월과 연도. 그것은 사용 단락 비트 마스크 leapYear 모듈러스 알고리즘 (약간 JS 위해 수정) 및 공통 모드-8 달 알고리즘. 0

에주의 AD/BC표기 년 0 AD가 / BC가 존재하지 않는이 : 대신 올해는 1 BC도약 년입니다!
BC 표기법을 설명해야한다면 먼저 연도 값 (그렇지 않으면 양수)에서 1 년을 빼면됩니다 !! (또는 1추가 연도 계산 위해 연도를 뺍니다 .)

function daysInMonth(m, y){
  return m===2?y&3||!(y%25)&&y&15?28:29:30+(m+(m>>3)&1);
}
<!-- example for the snippet -->
<input type="text" value="enter year" onblur="
  for( var r='', i=0, y=+this.value
     ; 12>i++
     ; r+= 'Month: ' + i + ' has ' + daysInMonth(i, y) + ' days<br>'
     );
  this.nextSibling.innerHTML=r;
" /><div></div>

월은 1부터 시작해야합니다!

여기에서는 윤년에 대한 추가 분기가 2 월에만 필요하기 때문에 Javascript 에서 사용한 매직 넘버 조회와 다른 알고리즘이 1 년 (1-366) 답변을 계산합니다 .


moment.js 당신은 daysInMonth () 메소드를 사용할 수 있습니다 :

moment().daysInMonth(); // number of days in the current month
moment("2012-02", "YYYY-MM").daysInMonth() // 29
moment("2012-01", "YYYY-MM").daysInMonth() // 31

혼란을 없애기 위해 현재 1 기반이므로 월 문자열을 기반으로 할 것입니다.

function daysInMonth(month,year) {
    monthNum =  new Date(Date.parse(month +" 1,"+year)).getMonth()+1
    return new Date(year, monthNum, 0).getDate();
}

daysInMonth('feb', 2015)
//28

daysInMonth('feb', 2008)
//29

한 줄 직접 계산 (Date 객체 없음) :

function daysInMonth(m, y) {//m is 1-based, feb = 2
   return 31 - (--m ^ 1? m % 7 & 1:  y & 3? 3: y % 25? 2: y & 15? 3: 2);
}

console.log(daysInMonth(2, 1999)); // February in a non-leap year
console.log(daysInMonth(2, 2000)); // February in a leap year

0 기반 월의 변형 :

function daysInMonth(m, y) {//m is 0-based, feb = 1
   return 31 - (m ^ 1? m % 7 & 1:  y & 3? 3: y % 25? 2: y & 15? 3: 2);
}

If you want the number of days in the current month of a Date object, consider the following method:

Date.prototype.getNumberOfDaysInMonth = function(monthOffset) {
    if (monthOffset !== undefined) {
        return new Date(this.getFullYear(), this.getMonth()+monthOffset, 0).getDate();
    } else {
        return new Date(this.getFullYear(), this.getMonth(), 0).getDate();
    }
}

Then you can run it like this:

var myDate = new Date();
myDate.getNumberOfDaysInMonth(); // Returns 28, 29, 30, 31, etc. as necessary
myDate.getNumberOfDaysInMonth(); // BONUS: This also tells you the number of days in past/future months!

In a single line:

// month is 1-12
function getDaysInMonth(year, month){
    return month == 2 ? 28 + (year % 4 == 0 ? (year % 100 == 0 ? (year % 400 == 0 ? 1 : 0) : 1):0) : 31 - (month - 1) % 7 % 2;
}

Here is goes

new Date(2019,2,0).getDate(); //28
new Date(2020,2,0).getDate(); //29

function numberOfDays(iMonth, iYear) {
         var myDate = new Date(iYear, iMonth + 1, 1);  //find the fist day of next month
         var newDate = new Date(myDate - 1);  //find the last day
            return newDate.getDate();         //return # of days in this month
        }

Considering leap years:

function (year, month) {
    var isLeapYear = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);

    return [31, (isLeapYear ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}

Perhaps not the most elegant solution, but easy to understand and maintain; and, it's battle-tested.

function daysInMonth(month, year) {
    var days;
    switch (month) {
        case 1: // Feb, our problem child
            var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
            days = leapYear ? 29 : 28;
            break;
        case 3: case 5: case 8: case 10: 
            days = 30;
            break;
        default: 
            days = 31;
        }
    return days;
},

참고URL : https://stackoverflow.com/questions/315760/what-is-the-best-way-to-determine-the-number-of-days-in-a-month-with-javascript

반응형