Reputation: 1346
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
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
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
Upvotes: 0
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
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
Reputation: 20418
Try this
var mymonth=new Date().getMonth();
alert((mymonth).toString().length);
Upvotes: 0
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
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);
Upvotes: 0