H Varma H Varma - 1 month ago 4
Javascript Question

How to convert yyyy-mm-dd to dd-Mon-yyyy (with month name) using javascript

I have a date format as 2016-01-09.Now I want to convert this date format in to 09-Jan-2016 I was able to convert in to 09-01-2016.But how can i get the month name added there.can someone help..
Here is the code which iam trying

function formatDate(input){
var datePart = input.match(/\d+/g),
year = datePart[0].substring(0,4), // get only two digits
month = datePart[1], day = datePart[2];

return day+'-'+month+'-'+year;
}
formatDate ('2010-01-18'); // "18-01-2010"

Answer

Try this

function formatDate(d) 
        {
          var date = new Date(d);

         if ( isNaN( date .getTime() ) ) 
         {
            return d;
         }
         else
        {
          
          var month = new Array();
          month[0] = "Jan";
          month[1] = "Feb";
          month[2] = "Mar";
          month[3] = "Apr";
          month[4] = "May";
          month[5] = "Jun";
          month[6] = "Jul";
          month[7] = "Aug";
          month[8] = "Sept";
          month[9] = "Oct";
          month[10] = "Nov";
          month[11] = "Dec";

          day = date.getDate();
          
          if(day < 10)
          {
             day = "0"+day;
          }
          
          return    day  + " " +month[date.getMonth()] + " " + date.getFullYear();
          }
            
         }


date_response = formatDate('2016-10-25');

alert(date_response)

Comments