Obteniendo la fecha y hora actuales en JavaScript
Tengo un script que imprime la fecha y hora actuales en JavaScript, pero la FECHA siempre es incorrecta. Aquí está el código:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDay() + "/" + currentdate.getMonth()
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Debería imprimir 18/04/2012 15:07:33 y imprime 3/3/2012 15:07:33
Respuesta #1
.getMonth() devuelve un número basado en cero, por lo que para obtener el mes correcto necesitas sumar 1, así que llamar a .getMonth() en mayo devolverá 4 y no 5.
Entonces, en tu código podemos usar currentdate.getMonth()+1 para mostrar el valor correcto. Además:
.getDate()devuelve el día del mes <- este es el que quieres.getDay()es un método separado del objetoDateque devolverá un número entero que representa el día actual de la semana (0-6)0 == Domingoetc
así que tu código debería verse así:
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
Las instancias de JavaScript Date heredan de Date.prototype. Puedes modificar el objeto prototype del constructor para afectar las propiedades y métodos heredados por las instancias de JavaScript Date
Puedes hacer uso del objeto prototipo Date para crear un nuevo método que devolverá la fecha y hora de hoy. Estos nuevos métodos o propiedades serán heredados por todas las instancias del objeto Date, lo que los hace especialmente útiles si necesitas reutilizar esta funcionalidad.
// For todays date;
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
Luego simplemente puedes obtener la fecha y la hora haciendo lo siguiente:
var newDate = new Date();
var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();
O llama al método en línea para que simplemente sea -
var datetime = "LastSync: " + new Date().today() + " @ " + new Date().timeNow();
Respuesta #2
Para obtener la hora y la fecha debes usar
new Date().toLocaleString();
>> "09/08/2014, 2:35:56 AM"
Para obtener solo la fecha, deberías usar
new Date().toLocaleDateString();
>> "09/08/2014"
Para obtener solo la hora, deberías usar
new Date().toLocaleTimeString();
>> "2:35:56 AM"
O si solo quieres la hora en el formato hh:mm sin AM/PM para el inglés estadounidense
new Date().toLocaleTimeString('en-US', { hour12: false,
hour: "numeric",
minute: "numeric"});
>> "02:35"
o para el inglés británico
new Date().toLocaleTimeString('en-GB', { hour: "numeric",
minute: "numeric"});
>> "02:35"
Lee más aquí.
Respuesta #3
Para una salida verdadera al estilo MySQL, use la siguiente función: 2023-11-28 15:33:12
- Si haces clic en el botón 'Ejecutar fragmento de código' a continuación
- Te mostrará un ejemplo sencillo de reloj digital en tiempo real
- La demostración aparecerá debajo del fragmento de código.
function getDateTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth()+1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
if(month.toString().length == 1) {
month = '0'+month;
}
if(day.toString().length == 1) {
day = '0'+day;
}
if(hour.toString().length == 1) {
hour = '0'+hour;
}
if(minute.toString().length == 1) {
minute = '0'+minute;
}
if(second.toString().length == 1) {
second = '0'+second;
}
var dateTime = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second;
return dateTime;
}
// example usage: realtime clock
setInterval(function(){
currentTime = getDateTime();
document.getElementById("digital-clock").innerHTML = currentTime;
}, 1000);<div id="digital-clock"></div>Respuesta #4
Solo usa:
var d = new Date();
document.write(d.toLocaleString());
document.write("<br>");
Respuesta #5
corta
Mejorando la respuesta de Steve para obtener exactamente lo que el OP pidió:
new Date().toLocaleString().replace(',','')
console.log(new Date().toLocaleString().replace(',',''));Respuesta #6
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Cambie el método .getDay() a .GetDate() y sume uno al mes, porque cuenta los meses desde 0.
Respuesta #7
Usando por defecto Date()
const now = new Date();
console.log(now); // Output: Thu Sep 23 2021 13:24:52 GMT-0400 (Eastern Daylight Time)
Para diferentes formatos de fecha y hora puedes usar toLocaleString():
Formato de fecha corta:
MM/DD/YYYYconst now = new Date(); const formattedDate = now.toLocaleString('en-US', { dateStyle: 'short' }); console.log(formattedDate); // Output: "9/23/2021"Formato de fecha larga:
Día de la semana, Mes Día, Añoconst now = new Date(); const formattedDate = now.toLocaleString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }); console.log(formattedDate); // Output: "Thursday, September 23, 2021"Formato de hora corta:
HH:MM AM/PMconst now = new Date(); const formattedDate = now.toLocaleString('en-US', { timeStyle: 'short' }); console.log(formattedDate); // Output: "1:24 PM"Formato de hora larga:
HH:MM:SS AM/PM Zona horariaconst now = new Date(); const formattedDate = now.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: true, timeZoneName: 'short' }); console.log(formattedDate); // Output: "1:24:52 PM EDT"Formato ISO 8601:
AAAA-MM-DDTHH:MM:SSZconst now = new Date(); const isoDate = now.toISOString(); console.log(isoDate); // Output: "2021-09-23T17:24:52.740Z"
