2012-05-17 27 views
27

Possible Duplicate:
Formatting a date in javascriptCómo formatear una fecha en formato MM/dd/aaaa HH: mm: ss en JavaScript?

sé otros formatos posibles en JavaScript objeto Date pero no he tenido sobre cómo formatear la fecha de MM/dd/yyyy HH:mm:ss formato.

Háganme saber si encuentra ese problema.

+0

Todos los métodos existen en el objeto de fecha. ¿Qué has intentado? – Corbin

+0

Hola Corbin, probé con algunos formatos predefinidos pero no obtuve un formato predefinido para MM/dd/aaaa HH: mm: ss – Gendaful

Respuesta

76

intentar algo como esto

var d = new Date, 
    dformat = [d.getMonth()+1, 
       d.getDate(), 
       d.getFullYear()].join('/')+' '+ 
       [d.getHours(), 
       d.getMinutes(), 
       d.getSeconds()].join(':'); 

Si desea cero de los valores < 10, utilizar esta extensión número

Number.prototype.padLeft = function(base,chr){ 
    var len = (String(base || 10).length - String(this).length)+1; 
    return len > 0? new Array(len).join(chr || '0')+this : this; 
} 
// usage 
//=> 3..padLeft() => '03' 
//=> 3..padLeft(100,'-') => '--3' 

Aplicado al código anterior:

var d = new Date, 
    dformat = [(d.getMonth()+1).padLeft(), 
       d.getDate().padLeft(), 
       d.getFullYear()].join('/') +' ' + 
       [d.getHours().padLeft(), 
       d.getMinutes().padLeft(), 
       d.getSeconds().padLeft()].join(':'); 
//=> dformat => '05/17/2012 10:52:21' 

Ver este código en jsfiddle

See also

+0

Gracias Kooilnc, probé var d = new Date(); var dformat = [d.getMonth(). Join ('/') + d.getDate(). Join ('/') + d.getFullYear()] join ('/') + '' + d. getHours(). join (':') + d.getMinutes(). join (':') + d.getSeconds()]; pero obtengo "SyntaxError no capturado: token inesperado"). ¿Sabe usted la razón? Gracias por la ayuda – Gendaful

+0

Su código es completamente incorrecto (no puede usar 'd.getMonth(). Join ('/')'). Intenta copiar/ejecutar el código que di en mi respuesta * sin cambiarlo *. He agregado un enlace jsfiddle para usted – KooiInc

+1

Su ejemplo es incorrecto. Está pidiendo MM/dd y ha suministrado el formato dd/MM (estilo europeo). –

2
var d = new Date(); 

var curr_date = d.getDate(); 

var curr_month = d.getMonth(); 

var curr_year = d.getFullYear(); 

document.write(curr_date + "-" + curr_month + "-" + curr_year); 

usar este puede dar formato a la fecha.

puede cambiar la apariencia de la forma que quieres, entonces

para obtener más información se puede visitar here

3
 

var d = new Date(); 

// calling the function 
formatDate(d,4); 


function formatDate(dateObj,format) 
{ 
    var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; 
    var curr_date = dateObj.getDate(); 
    var curr_month = dateObj.getMonth(); 
    curr_month = curr_month + 1; 
    var curr_year = dateObj.getFullYear(); 
    var curr_min = dateObj.getMinutes(); 
    var curr_hr= dateObj.getHours(); 
    var curr_sc= dateObj.getSeconds(); 
    if(curr_month.toString().length == 1) 
    curr_month = '0' + curr_month;  
    if(curr_date.toString().length == 1) 
    curr_date = '0' + curr_date; 
    if(curr_hr.toString().length == 1) 
    curr_hr = '0' + curr_hr; 
    if(curr_min.toString().length == 1) 
    curr_min = '0' + curr_min; 

    if(format ==1)//dd-mm-yyyy 
    { 
     return curr_date + "-"+curr_month+ "-"+curr_year;  
    } 
    else if(format ==2)//yyyy-mm-dd 
    { 
     return curr_year + "-"+curr_month+ "-"+curr_date;  
    } 
    else if(format ==3)//dd/mm/yyyy 
    { 
     return curr_date + "/"+curr_month+ "/"+curr_year;  
    } 
    else if(format ==4)// MM/dd/yyyy HH:mm:ss 
    { 
     return curr_month+"/"+curr_date +"/"+curr_year+ " "+curr_hr+":"+curr_min+":"+curr_sc;  
    } 
} 

+6

-1, codificación muy mala aquí – KooiInc

30
var d = new Date(); 
alert(
    ("00" + (d.getMonth() + 1)).slice(-2) + "/" + 
    ("00" + d.getDate()).slice(-2) + "/" + 
    d.getFullYear() + " " + 
    ("00" + d.getHours()).slice(-2) + ":" + 
    ("00" + d.getMinutes()).slice(-2) + ":" + 
    ("00" + d.getSeconds()).slice(-2) 
); 
+1

Debería usar getDate() para la fecha. No se puede editar porque SO quiere más de 6 caracteres editados ... suspiro. – Llyle

Cuestiones relacionadas