JavaScript converts the string to Date with the format (dd mmm yyyy) ie June 01, 2012

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

The 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

+6
source share
6 answers

Try the following:

 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

+8
source

As other users have already mentioned, "format" not a standard method of a Date object. You can do this without using any format (even if they are)

 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

+2
source
 return $.datepicker.formatDate('dd-M-yy', new Date(dateVal)); //01-Dec-2014 
+1
source

You can use javascript Intl https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat

The following example will show something like Nov 02, 2017

console.log(new Intl.DateTimeFormat('en-EN', { year: 'numeric', month: 'short', day: 'numeric' }).format(new Date()));

Milton.-

0
source

"format" is not a standard method of a Date object

-1
source
 dt.format("dd MMM yyyy") 

Use capital letters.

-4
source

Source: https://habr.com/ru/post/948615/


All Articles