user3386779 user3386779 - 3 years ago 97
Javascript Question

get month,date and year from given date

I want to get the month and date from the given date.I get server time .

date="Wed Jul 26 2017 11:39:44 GMT+0530 (India Standard Time)"
; I want to get mm/dd/yyyy from the given date

var xmlHttp;
function srvTime(){
try {
//FF, Opera, Safari, Chrome
xmlHttp = new XMLHttpRequest();
}
catch (err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (err2) {
try {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (eerr3) {
//AJAX not supported, use CPU time.
alert("AJAX not supported");
}
}
}
xmlHttp.open('HEAD',window.location.href.toString(),false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
return xmlHttp.getResponseHeader("Date");
}
var st = srvTime();
var date = new Date(st);
console.log(date); //Wed Jul 26 2017 11:39:44 GMT+0530 (India Standard Time)

Answer Source

You can use getDate(), getMonth() and getFullYear(). Add 1 to month as Javascript return months as 0 for January, 1 for February, etc.

var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

console.log('Day:' + day);
console.log('Month:' + month);
console.log('Year:' + year);

if(day < 10){
    day='0'+day;
} 
if(month<10){
    month='0'+month;
} 
var today = month+'/'+day+'/'+year;
console.log('Date:' + today);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download