Search code examples
javascriptdatedate-formattingdate-conversion

How to convert date format from dd-MMM-yyyy to yyyymmdd in Javascript?


I've an input text box with a date-picker, when the user selects a particular date, the date say 09-Dec-2014 gets applied to the input text box. On submit, I want the date to be passed to the server in yyyymmdd format say 20141209. So how to convert the date format in javascript?

var date = new Date(Date.parse('09-Dec-2014'));

Above code gives me 'Invalid date'.

Searched the net for solution but was not able to find for my problem.

Can someone help me out?

Thanks.


Solution

  • Thanks for the answers Danyal Sandeelo and Jeeva Jsb.

    I was able to get the date in yyyymmdd format using the code given below.

    var date = '09-Dec-2014'.split("-");
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    for(var j=0;j<months.length;j++){
        if(date[1]==months[j]){
             date[1]=months.indexOf(months[j])+1;
         }                      
    } 
    if(date[1]<10){
        date[1]='0'+date[1];
    }                        
    var formattedDate = date[2]+date[1]+date[0];