Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 665
Satinder singh Avatar asked Jul 03 '13 10:07

Satinder singh


2 Answers

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

like image 74
Chickenrice Avatar answered Oct 13 '22 06:10

Chickenrice


Since other users already mentioned that "format" is not a standard method of Date object. You can do it without using any format method (even if there exist any)

var t_sdate = "6/1/2012";
var sptdate = String(t_sdate).split("/");
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var myMonth = sptdate[0];
var myDay = sptdate[1];
var myYear = sptdate[2];
var combineDatestr = myDay + " " + months[myMonth - 1] + " " + myYear;

alert(combineDatestr);

JsFiddle Demo

like image 36
sohaiby Avatar answered Oct 13 '22 07:10

sohaiby