Reputation: 21
First post here. I am really curious exactly why the below function does not return the proper month/day/year answer and instead just returns 10.
If I remove the +1 from the var month it returns everything correct, except it is one month behind.
I am beginning to learn CS and any help is much appreciated. If I run this outside a function, it returns the correct answer.
function todaydate() {
var today = new Date();
var month = today.getMonth()+1;
var day = today.getDate();
var year = today.getFullYear();
if (month < 10) {
month = "0" + month
} else {
return month
}
return console.log(month + "/" + day + "/" + year)
}
Hopefully this question is helpful to a broader audience on how functions actually run.
EDIT: Thanks everyone, this makes a lot of sense. I really appreciate all your pedantic answers and perspective.
Upvotes: 2
Views: 57
Reputation: 7777
If the month is >= 10, then you return the month,
} else {
return month
}
otherwise you return
return console.log(month + "/" + day + "/" + year)
returning console.log probably doesn't return anything
So of course your function is returning inconsistent things.
But I would also advise you to use the excellent momentjs
It can do what you want in one line:
moment().format("DD/MM/YYYY");
It makes handling date and time easier and more consistent
Upvotes: 1
Reputation:
The else
is unnecessary. Do it like this:
function todaydate() {
var today = new Date();
var month = today.getMonth() + 1;
var day = today.getDate();
var year = today.getFullYear();
if (month < 10) {
month = "0" + month
}
return month + "/" + day + "/" + year;
}
console.log(todaydate());
or like this:
function todaydate() {
var today = new Date();
var month = today.getMonth() + 1;
var day = today.getDate();
var year = today.getFullYear();
if (month < 10) {
month = "0" + month
}
console.log(month + "/" + day + "/" + year);
}
todaydate();
Upvotes: 0