Generalmente existen 3 tipos de formatos de entrada de fecha de JavaScript:
"2015-03-25" (La Norma Internacional)
"25/03/2015"
"25 de marzo de 2015" o "25 de marzo de 2015"
El formato ISO sigue un estándar estricto en JavaScript.
Los otros formatos no son muy bien definido y podría ser específico del navegador.
Independientemente del formato de entrada, JavaScript generará (de forma predeterminada) las fechas completas formato de cadena de texto:
ISO 8601 es el estándar internacional para la representación de fechas y veces.
La sintaxis ISO 8601 (AAAA-MM-DD) también es el formato de fecha JavaScript preferido:
const d = new Date("2015-03-25");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript ISO Dates</h2>
<p id="demo"></p>
<script>
const d = new Date("2015-03-25");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
La fecha calculada será relativa a su zona horaria.
Dependiendo de su zona horaria, el resultado anterior variará entre el 24 y el 25 de marzo.
Las fechas ISO se pueden escribir sin especificar el día (AAAA-MM):
const d = new Date("2015-03");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript ISO Dates</h2>
<p id="demo"></p>
<script>
const d = new Date("2015-03");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Las zonas horarias variarán el resultado anterior entre el 28 de febrero y el 01 de marzo.
Las fechas ISO se pueden escribir sin mes ni día (AAAA):
const d = new Date("2015");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript ISO Dates</h2>
<p id="demo"></p>
<script>
const d = new Date("2015");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Las zonas horarias variarán el resultado anterior entre el 31 de diciembre de 2014 y el 1 de enero de 2015.
Las fechas ISO se pueden escribir añadiendo horas, minutos y segundos (AAAA-MM-DDTHH:MM:SSZ):
const d = new Date("2015-03-25T12:00:00Z");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript ISO Dates</h2>
<p>Separate date and time with a capital T.</p>
<p>Indicate UTC time with a capital Z.</p>
<p id="demo"></p>
<script>
const d = new Date("2015-03-25T12:00:00Z");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
La fecha y la hora están separadas por T mayúscula.
La hora UTC se define con una letra mayúscula Z.
Si desea modificar la hora relativa a UTC, elimine la Z y agregue +HH:MM o -HH:MM en cambio:
const d = new Date("2015-03-25T12:00:00-06:30");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript ISO Dates</h2>
<p>Modify the time relative to UTC by adding +HH:MM or subtraction -HH:MM to the time.</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
new Date("2015-03-25T12:00:00-06:00");
</script>
</body>
</html>
UTC (hora universal coordinada) es lo mismo que GMT (hora media de Greenwich).
Omitir T o Z en una cadena de fecha y hora puede dar resultados diferentes en diferentes navegadores.
Al establecer una fecha, sin especificar la zona horaria, JavaScript utilizará la zona horaria del navegador.
Al obtener una fecha, sin especificar la zona horaria, el resultado es convertido a la zona horaria del navegador.
En otras palabras: si se crea una fecha/hora en GMT (hora media de Greenwich), la La fecha/hora se convertirá a CDT (hora de verano central de EE. UU.) si un usuario navega del centro de EE.UU.
Las fechas cortas se escriben con una sintaxis "MM/DD/AAAA" como esta:
const d = new Date("03/25/2015");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date("03/25/2015");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
En algunos navegadores, los meses o días sin ceros a la izquierda pueden producir un error:
const d = new Date("2015-3-25");
El comportamiento de "AAAA/MM/DD" no está definido.
Algunos navegadores Intenta adivinar el formato. Algunos devolverán NaN.
const d = new Date("2015/03/25");
El comportamiento de "DD-MM-AAAA" tampoco está definido.
Algunos navegadores Intenta adivinar el formato. Algunos devolverán NaN.
const d = new Date("25-03-2015");
Las fechas largas suelen escribirse con una sintaxis "MMM DD AAAA" como esta:
const d = new Date("Mar 25 2015");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date("Mar 25 2015");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
El mes y el día pueden estar en cualquier orden:
const d = new Date("25 Mar 2015");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date("25 Mar 2015");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Y el mes se puede escribir completo (enero) o abreviado (enero):
const d = new Date("January 25 2015");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date("January 25 2015");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
const d = new Date("Jan 25 2015");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date("Jan 25 2015");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Se ignoran las comas. Los nombres no distinguen entre mayúsculas y minúsculas:
const d = new Date("JANUARY, 25, 2015");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript new Date()</h2>
<p id="demo"></p>
<script>
const d = new Date("JANUARY, 25, 2015");
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Si tiene una cadena de fecha válida, puede usar Método Date.parse()
para convertirlo a milisegundos.
Date.parse()
devuelve el número de milisegundos entre la fecha y enero 1, 1970:
let msec = Date.parse("March 21, 2012");
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Date.parse()</h2>
<p>Date.parse() returns the number of milliseconds between the date and January 1, 1970:</p>
<p id="demo"></p>
<script>
const msec = Date.parse("March 21, 2012");
document.getElementById("demo").innerHTML = msec;
</script>
</body>
</html>
Luego puedes usar la cantidad de milisegundos para convertirlo en un objeto de fecha:
let msec = Date.parse("March 21, 2012");
const d = new Date(msec);
Pruébelo usted mismo →
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Date.parse()</h2>
<p>Date.parse(string) returns milliseconds.</p>
<p>You can use the return value to convert the string to a date object:</p>
<p id="demo"></p>
<script>
let msec = Date.parse("March 21, 2012");
const d = new Date(msec);
document.getElementById("demo").innerHTML = d;
</script>
</body>
</html>
Para obtener una referencia completa de la fecha, visite nuestro:
Referencia completa de fechas de JavaScript.
La referencia contiene descripciones y ejemplos de todas las propiedades de fecha y métodos.