find number of days for given month and year in nodejs

I am trying to get number of days for given month and year in node.js

npm i date-and-time is install in node

dailyCalibRptTempTbl(req){
    return new Promise((resolve,reject) => {
        let responseObj = {};
        var str_date = req.body.date;
        var year = str_date.split('-')[0];
        var month = str_date.split('-')[1];
        var day = this.getNumOfDays(year,month);
        console.log(day);
    })
}

getNumOfDays(y,m){
    var days = date(y, m, 0).getDate();
    return days;
}

expect then in 31 days for month 3 and year 2019

Upvotes: 0

Views: 527

Answers (2)

Shekar Mania
Shekar Mania

Reputation: 325

Using Moment js It is very easy to find the number of days in a given month.

Suppose your date format is 2019-03-30 you want to know the number of days in 2019-03

const moment = require('moment')

moment('2019-03', 'YYYY-MM').daysInMonth()

For Number of days in a given year, Check if the given year is a leap year or not, if it is a leap year, number of days = 366, else 365.

let isLeapYear = moment([2019]).isLeapYear()

let numOfDaysInYear = 365
if(isLeapYear){
  numOfDayInYear = 366
}

Upvotes: 0

vels4j
vels4j

Reputation: 11298

Use new Date as like below

function getNumOfDays(y, m) {
    return new Date(y, m, 0).getDate();
}

Upvotes: 1

Related Questions