[Javascript] Convert a date from YYYY-MM-DD to Month DD, YYYY

Hola a tutti,

oggi avevo il bisogno di convertire una data di tipo YYYY-MM-DD (MySQL Format) in una data in stile americano Month DD, YYYY.

Esempio:

Da 2013-01-01 a Jan 01, 2013

Per fare ciò in javascript ho sviluppato una piccola funzione per la conversione della data:

function formatDate(input) {
	var datePart = input.match(/\d+/g),
	year  = datePart[0].substring(0), 
	month = datePart[1], 
	day = datePart[2];
 
	if(month < 10) {
		month = month.substring(1);
	} 
 
	var month_arr = new Array();
 
	month_arr[1]="Jan";
	month_arr[2]="Feb";
	month_arr[3]="Mar";
	month_arr[4]="Apr";
	month_arr[5]="May";
	month_arr[6]="Jun";
	month_arr[7]="Jul";
	month_arr[8]="Aug";
	month_arr[9]="Sep";
	month_arr[10]="Oct";
	month_arr[11]="Nov";
	month_arr[12]="Dec";
	var month_final = month_arr[parseInt(month)]; 
 
	return month_final+' '+day+', '+year;      
 
 
}

Ecco una demo per il corretto utilizzo: http://jsfiddle.net/7xVRe/

Spero sarà utile a qualcuno, saluti :D

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *

È possibile utilizzare questi tag ed attributi XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>