-2

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)
user3386779
  • 6,883
  • 20
  • 66
  • 134

3 Answers3

0

You can use the following methods:

var yyyy = date.getFullYear();
var mm = date.getMonth();
var dd = date.getDay();
JSON Derulo
  • 9,780
  • 7
  • 39
  • 56
0

Best way would be to write custom code, something like this.

  function formatDate(date) {
      var day = date.getDate();
      var month = date.getMonth();
      var year = date.getFullYear();

      return (month+1) + '/' + day + '/' + year;
    }

    console.log(formatDate(new Date())); 
Abhishek Singh
  • 10,243
  • 22
  • 74
  • 108
0

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);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • You should not answer questions that are obvious duplicates, particularly where the OP has not made any attempt to write their own code. This question has been asked many, many times before. Searching on [*javascript format date*](https://stackoverflow.com/search?q=%5Bjavascript%5D+format+date) returns 22,000 results just here on StackOverflow. – RobG Jul 26 '17 at 08:43