Friend
Friend

Reputation: 1346

simple jquery string count not working

here is my code below...

var mymonth=new Date().getMonth();
console.log((mymonth).length);

I am getting an error undefined in console.. i have already tried..

console.log((new Date().getMonth()).length);

but still the same error...Iam supposed to get the length of month 1 whats the issue with this???

Upvotes: 1

Views: 139

Answers (7)

Sam-Graham
Sam-Graham

Reputation: 1360

The .length operator doesn't return the number of days in the month, that is more for arrays and strings.

What you need is to take advantage of the Date object constructor!

function getDaysInMonth(year, day) {
    return new Date(year, day, 0).getDate();
}

Just pass in your date object before console.log, like this

console.log( getDaysInMonth( Date().getYear(), mymonth) );

Upvotes: 0

Suraj Rawat
Suraj Rawat

Reputation: 3763

You need to parse the date/month to string coz by default it gives an integer value and length property only work with string , object or array types !

var mymonth=String(new Date().getMonth());
console.log(mymonth.length);

will give you 1 as a o/p

Live example

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

getMonth returns int value and it does not have length property. You need to make it string first and then call length.

var mymonth=new Date().getMonth();
console.log(mymonth.toString().length);

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

mymonth is a numerical value which does not have the length property, so try

var mymonth=new Date().getMonth();
console.log((''+ mymonth).length);

or use a numerical comparison like below to check whether the month is of 2 digits or not

mymonth < 10

Upvotes: 2

Sridhar R
Sridhar R

Reputation: 20418

Try this

var mymonth=new Date().getMonth();
alert((mymonth).toString().length);

Upvotes: 0

NcDreamy
NcDreamy

Reputation: 805

You need to convert the date value to string and then count the length. Try this:

var mymonth=new Date().getMonth();
console.log(mymonth.toString().length);

Upvotes: 0

Sudharsan S
Sudharsan S

Reputation: 15393

It is in date format so you convert to string first and count the length.Use .toString() in javascript

var mymonth=new Date().getMonth();
console.log(mymonth.toString().length);

DEMO

Upvotes: 0

Related Questions