There are two problems here.
First, you're using the currentdate
variable without first declaring it. This is easy enough to fix by adding in var currentdate = new Date();
Second, the getter methods on a Date
object don't return with leading zeros. This means you need to get the value and check if it's less than 9. If it is, you need to add in a leading zero.
Something like:
$(document).ready(function () {
var currentdate=new Date() // Declare date variable
var datetime = "" + currentdate.getFullYear();
var month = currentdate.getMonth() + 1; // Month is 0-11, not 1-12
if (month < 10) {
month = '0' + month;
}
datetime += month;
var day = currentdate.getDate();
if (day < 10) {
day = '0' + day;
}
datetime += day;
var hours = currentdate.getHours();
if (hours < 10) {
hours = '0' + hours;
}
datetime += hours;
var minutes = currentdate.getMinutes();
if (minutes < 10) {
minutes = '0' + minutes;
}
datetime += minutes;
var seconds = currentdate.getSeconds();
if (seconds < 10) {
seconds = '0' + seconds;
}
datetime += seconds;
alert(datetime);
});