JavaScript convert string into Date with format (dd mmm yyyy) i.e. 01 Jun 2012

Satinder singh picture Satinder singh · Jul 3, 2013 · Viewed 67.5k times · Source

I am getting a string variable having date in format 6/1/2012, I want to convert it into 01 Jun 2012 . JS FIDDLE DEMO

Code I tried:

var t_sdate="6/1/2012";                  
var sptdate = String(t_sdate).split("/");
var myMonth = sptdate[0];
var myDay = sptdate[1];
var myYear = sptdate[2];
var combineDatestr = myYear + "/" + myMonth + "/" + myDay;

var dt = new Date(combineDatestr);
var formatedDate= dt.format("dd mmm yyyy")
alert(formatedDate);

Getting output as 01 000 2012, required as 01 Jun 2012

Answer

Chickenrice picture Chickenrice · Jul 3, 2013

Try this:

function getFormattedDate(input) {
    var pattern = /(.*?)\/(.*?)\/(.*?)$/;
    var result = input.replace(pattern,function(match,p1,p2,p3){
        var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        return (p2<10?"0"+p2:p2) + " " + months[(p1-1)] + " " + p3;
    });

    alert(result);
}

getFormattedDate("6/1/2013");

Jsfiddle demo