¿Cómo obtengo la fecha actual en JavaScript?
¿Cómo obtengo la fecha actual en JavaScript?
30 answers
Use new Date()
para generar un nuevo objeto Date
que contenga la fecha y hora actuales.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
today = mm + '/' + dd + '/' + yyyy;
document.write(today);
Esto le dará la fecha de hoy en formato mm/dd/aaaa.
Simplemente cambia today = mm +'/'+ dd +'/'+ yyyy;
al formato que desees.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-21 09:24:10
var utc = new Date().toJSON().slice(0,10).replace(/-/g,'/');
document.write(utc);
Use la opción replace
si va a reutilizar la variable utc
, como new Date(utc)
, ya que Firefox y Safari no reconocen una fecha con guiones.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-27 18:47:20
ACTUALIZADO!, Desplácese hacia abajo
Si quieres algo bonito simple para el usuario final ... Also, fixed a small suffix issue in the first version below. Now properly returns suffix.
var objToday = new Date(),
weekday = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
dayOfWeek = weekday[objToday.getDay()],
domEnder = function() { var a = objToday; if (/1/.test(parseInt((a + "").charAt(0)))) return "th"; a = parseInt((a + "").charAt(1)); return 1 == a ? "st" : 2 == a ? "nd" : 3 == a ? "rd" : "th" }(),
dayOfMonth = today + ( objToday.getDate() < 10) ? '0' + objToday.getDate() + domEnder : objToday.getDate() + domEnder,
months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),
curMonth = months[objToday.getMonth()],
curYear = objToday.getFullYear(),
curHour = objToday.getHours() > 12 ? objToday.getHours() - 12 : (objToday.getHours() < 10 ? "0" + objToday.getHours() : objToday.getHours()),
curMinute = objToday.getMinutes() < 10 ? "0" + objToday.getMinutes() : objToday.getMinutes(),
curSeconds = objToday.getSeconds() < 10 ? "0" + objToday.getSeconds() : objToday.getSeconds(),
curMeridiem = objToday.getHours() > 12 ? "PM" : "AM";
var today = curHour + ":" + curMinute + "." + curSeconds + curMeridiem + " " + dayOfWeek + " " + dayOfMonth + " of " + curMonth + ", " + curYear;
document.getElementsByTagName('h1')[0].textContent = today;
<h1></h1>
UBBER UPDATE Después de mucha dilación, finalmente heGitHubbed y actualizado esto con la solución final que he estado usando para mí. Incluso ha tenido algunas ediciones de último minuto para hacerlo más dulce! Si usted está buscando el viejo jsFiddle, por favor vea esto .
Esta actualización llega 2 sabores, todavía relativamente pequeño, aunque no tan pequeño como mi anterior, respuesta original. Si quieres extremadamente pequeño, ve con eso.
También tenga en cuenta: Esto es aún menos hinchado que el momento.js. Mientras momento.js es agradable, imo, tiene muchos métodos seculares, que requieren momento de aprendizaje como si fuera un idioma. El mío aquí usa el mismo formato común que PHP:date .
Rápido Enlaces
- Fecha.formato.min.js 5.08 KB
- DateFormat.min.js 4.16 KB
Sabor 1
new Date().format(String)
Mi Favorito Personal. Conozco el tabú, pero funciona muy bien en el Objeto de Fecha. Solo tenga en cuenta cualquier otro mods que pueda tener para el Objeto Date.
// use as simple as
new Date().format('m-d-Y h:i:s'); // 07-06-2016 06:38:34
Sabor 2
dateFormat(Date, String)
Método todo en uno más tradicional. Tiene toda la capacidad de la anterior, pero se llama a través de método con Fecha param.
// use as simple as
dateFormat(new Date(), 'm-d-Y h:i:s'); // 07-06-2016 06:38:34
Sabor ADICIONAL (requiere jQuery)
$.date(Date, String)
Esto contiene mucho más que una simple opciónformat
. Extiende el objeto base Date e incluye métodos comoaddDays
. Para obtener más información, consulte el Git.
En este mod, los caracteres de formato están inspirados en PHP:date. Para obtener una lista completa, consulte mi README
Este mod también tiene un lista de formatos pre-hechos. Para utilizar un formato preconfigurado, simplemente introduzca su nombre de clave. dateFormat(new Date(), 'pretty-a');
- 'compuesto'
- 'commonLogFormat' == 'd/M/Y:G:i:s'
- 'exif' = = 'Y:m:d G:i:s'
- 'isoYearWeek' = = 'Y\\WW'
- 'isoYearWeek2' = = 'Y-\\WW'
- 'isoYearWeekDay' = = 'Y\\WWj'
- 'isoYearWeekDay2' = = 'Y-\\WW-j'
- 'MySQL' == 'Y-m-d h: i: s'
- 'PostgreSQL' = = 'Y. z'
- 'postgreSQL2' == 'Yz'
- ' soap' == "Y-m-d \ \ TH: i:s. u"
- 'soap2' = = 'Y-m-d\\TH:i:s. uP'
- 'unixTimestamp' == '@U'
- 'xmlrpc' = = 'Ymd\\TG:i:s'
- 'xmlrpcCompact' = = 'Ymd\\TGIs'
- 'wddx' = = 'Y-n-j\\TG:i:s'
- 'constantes'
- ' AMERICAN ' = = 'F j Y' {[51]]}
- 'AMERICANSHORT' = = 'm/d/Y'
- 'AMERICANSHORTWTIME' = = 'm/d/Y h:i:sA'
- ' ATOM '= = 'Y-m-d\ \ TH: i: sP'
- 'COOKIE' = = 'l d-M-Y H:i: s T'
- "EUROPEO" = = " j F Y '
- 'EUROPEANSHORT' == 'd.m.Y'
- "EUROPEANSHORTWTIME" = = "d.m.Y H:i:s"
- 'ISO8601' = = 'Y-m-d\\TH:i:sO'
- 'LEGAL' == 'j F Y'
- 'RFC822' = = 'D d M y H:i: s O'
- 'RFC850' = = 'l d-M-y H: i: s T'
- 'RFC1036' = = 'D d M y H:i:s O'
- 'RFC1123' = = 'D d M Y H:i: s O'
- 'RFC2822' = = 'D d M Y H:i: s O'
- 'RFC3339' = = 'Y-m-d\\TH:i:sP'
- ' RSS ' = = 'D d M Y H:i:s O' {[51]]}
- 'W3C'= = "Y-m-d \ \ TH: i: sP"
- 'bonita'
- 'pretty-a' == 'g:i.sA l jS \ \ o \ \ f F Y'
- 'pretty-b' == 'g:iA l jS \\o\\f F Y'{[51]]}
- 'pretty-c' == 'n/d/Y g:iA'
- 'pretty-d' == 'n/d/Y'{[51]]}
- 'pretty-e' == 'F jS - g:ia'{[51]]}
- 'pretty-f' == 'g:iA'{[51]]}
Como puede notar, puede usar double \
para escapar de un carácter.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-20 14:24:54
Si solo desea una fecha sin información de hora, use:
var today = new Date();
today.setHours(0, 0, 0, 0);
document.write(today);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-08 15:23:03
Prueba esto:
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
El resultado será como
15/2/2012
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-10 11:20:31
Lo más corto posible.
Para obtener un formato como "2018-08-03":
let today = new Date().toISOString().slice(0, 10)
console.log(today)
Para obtener un formato como "8/3/2018":
let today = new Date().toLocaleDateString()
console.log(today)
También puede pasar locale como argumento, por ejemplo toLocaleDateString("sr")
, etc.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-05 21:09:24
Si está buscando un control mucho más granular sobre los formatos de fecha, le recomiendo revisar momentjs. Excelente biblioteca-y solo 5KB. http://momentjs.com /
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-12 01:03:28
Puedes usar el momento.js: http://momentjs.com /
var m = moment().format("DD/MM/YYYY");
document.write(m);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-08 15:28:51
var d = (new Date()).toString().split(' ').splice(1,3).join(' ');
document.write(d)
Para dividirlo en pasos:
(new Date()).toString()
da " Vie Jun 28 2013 15:30:18 GMT-0700 (PDT)"(new Date()).toString().split(' ')
divide la cadena anterior en cada espacio y devuelve una matriz de la siguiente manera: ["Fri", "Jun", "28", "2013", "15:31:14", "GMT-0700", " (PDT)"](new Date()).toString().split(' ').splice(1,3).join(' ')
toma el segundo, tercer y cuarto valores de la matriz anterior, los une con espacios y devuelve una cadena "Jun 28 2013"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-08 15:22:27
var date = new Date().toLocaleDateString("en-US");
Además, puede llamar al método toLocaleDateString
con dos parámetros:
var date = new Date().toLocaleDateString("en-US", {
"year": "numeric",
"month": "numeric"
});
Artículo sobre MSDN . Más información sobre este método en MDN .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-22 17:18:02
Esto funciona siempre:
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
document.write(today);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-05 19:07:18
Más limpio, versión más simple:
new Date().toLocaleString();
El resultado varía según la configuración regional del usuario :
2/27/2017, 9:15:41 AM
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-27 07:19:40
Puede usar Fecha.js biblioteca que amplía el objeto Date, por lo que puede tener .método today ().
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-26 13:00:15
Si está satisfecho con el formato AAAA-MM-DD, esto también hará el trabajo.
new Date().toISOString().split('T')[0]
2018-03-10
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-10 14:48:28
Puede obtener la fecha actual llamar al método estático ahora de la siguiente manera:
var now = Date.now()
Referencia:
Https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/now
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-11 20:03:58
La respuesta de Varun no da cuenta de Zona horaria. Aquí hay una versión que lo hace:
var d = new Date()
new Date(d.getTime() - d.getTimezoneOffset() * 60000).toJSON().slice(0, 10) // 2015-08-11
El TimezoneOffset
es minutos, mientras que el constructor de Fecha toma milisegundos, por lo tanto la multiplicación por 60000
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:27
Si quieres un formato simple DD/MM/YYYY
, acabo de llegar con esta solución simple, aunque no prefijo ceros que faltan.
var d = new Date();
document.write( [d.getDate(), d.getMonth()+1, d.getFullYear()].join('/') );
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 08:10:36
new Date().toDateString();
Resultado:
"Mie Feb 03 2016"
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-03 12:08:37
La respuesta más corta es: new Date().toJSON().slice(0,10)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-01 21:43:24
new Date().toISOString().slice(0,10);
También funcionaría
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-01 16:19:05
Puedes usar esto
<script>
function my_curr_date() {
var currentDate = new Date()
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var my_date = month+"-"+day+"-"+year;
document.getElementById("dateField").value=my_date;
}
</script>
El HTML es
<body onload='return my_curr_date();'>
<input type='text' name='dateField' id='dateField' value='' />
</body>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-19 19:17:38
Si está utilizando jQuery. Prueba este liner:
$.datepicker.formatDate('dd/mm/yy', new Date());
Aquí está la convención para formatear la fecha
- d-día del mes (sin cero inicial)
- dd-día del mes (dos dígitos)
- o-día del año (sin ceros a la izquierda)
- oo - día del año (tres dígitos)
- Nombre del día D corto
- DD-nombre del día largo
- m-mes del año (sin cero inicial)
- mm-mes del año (dos dígitos)
- M-nombre del mes corto
- MM - nombre del mes long
- año-y (dos dígitos)
- yy - año (cuatro dígitos)
Aquí está la referencia para jQuery datepicker
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-01 11:50:51
Una solución JS de una línea:
Tl;dr
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
edge, ff último, y retorno de chrometodaysDate = "2/7/2017"
"obras" * en IE10 +
EDITAR 2/7/2017
Me enteré de que IE10 e IE Edge hacer las cosas un poco diferente.. imagínate.
con new Date(Date.now()).toLocaleString()
como entrada,
IE10 devuelve:
"Tuesday, February 07, 2017 2:58:25 PM"
Podría escribir una gran función larga y FTFY. Pero usted realmente debe utilizar momento.js para estas cosas. Mi script simplemente limpia esto y te da la expandida notación tradicional estadounidense: > todaysDate = "March 06, 2017"
IE EDGE devuelve:
"2/7/2017 2:59:27 PM"
Por supuesto que no podría ser tan fácil. La cadena de fecha de Edge tiene caracteres "•" invisibles entre cada uno visible. Así que ahora no solo comprobaremos si el primer carácter es un número, sino los primeros 3 caracteres, ya que resulta que cualquier carácter en todo el rango de fechas eventualmente será un punto o una barra diagonal en algún momento. Así que mantenga las cosas simples, solo .cortar () los tres primeros caracteres (pequeño búfer contra futuras travesuras) y luego comprobar los números. Probablemente debe tenerse en cuenta que estos puntos invisibles podrían persistir en su código. Tal vez profundizaría en eso si tienes planes más grandes que solo imprimir esta cadena a tu vista.
∴ actualización de un solo liner:
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
Eso apesta para leer. ¿Qué tal:
var dateString = new Date(Date.now()).toLocaleString();
var todaysDate = dateString.slice(0,3).match(/[0-9]/i) ? dateString.split(' ')[0].split(',')[0] : dateString.split(' ')[1] + " " + dateString.split(' ')[2] + " " + dateString.split(' ')[3];
RESPUESTA ORIGINAL
Tengo un una sola línea para usted:
new Date(Date.now()).toLocaleString().split(', ')[0];
Y [1]
te dará la hora del día.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-07 18:55:49
Como toISOString()
solo devolverá la hora UTC actual , no la hora local. Tenemos que hacer una cita usando'.Función toString () ' para obtener la fecha en formato yyyy-MM-dd
como
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('T')[0]);
Para obtener la fecha y la hora en el formato yyyy-MM-ddTHH:mm:ss
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0]);
Para obtener la fecha y la hora en el formato yyyy-MM-dd HH:mm:ss
document.write(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString().split('.')[0].replace('T',' '));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-18 07:27:16
Usted puede pagar esto
var today = new Date();
today = parseInt(today.getMonth()+1)+'/'+today.getDate()+'/'+today.getFullYear()+"\nTime : "+today.getHours()+":"+today.getMinutes()+":"+today.getSeconds();
document.write(today);
Y vea la documentación de Date () constructor. link
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-11 06:31:18
Cuál es el problema con esto.. La forma más limpia de hacer esto es
var currentDate=new Date().toLocaleString().slice(0,10);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-31 19:39:27
Creo que esta es una vieja pregunta, pero la forma más fácil sería la siguiente:
var date = new Date();
var TimeStamp = date.toLocaleString();
function CurrentTime(){
alert(TimeStamp);
}
Esto tomará la hora actual, la pasará a una cadena basada en la ubicación y luego puede llamar a la función currentTime para mostrar la hora. Esta sería, para mí, la forma más efectiva de obtener una marca de tiempo para algo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-19 22:21:47
var dateTimeToday = new Date();
var dateToday = new Date(
dateTimeToday.getFullYear(),
(dateTimeToday.getMonth() + 1) /*Jan = 0! */,
dateTimeToday.getDate(),
0,
0,
0,
0);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-12 16:07:32
No se si va a ayudar a nadie, pero estoy usando esto para obtener el objeto de fecha de hoy.
new Date( 3600000*Math.floor(Date.now()/3600000) )
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-01 15:25:15
Esto puede ayudarte
var date = new Date();
console.log(date.getDate()+'/'+(date.getMonth()+1)+'/'+date.getFullYear());
Esto imprimirá la fecha actual en formato dd/MM/aaaa
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-17 08:33:10