Obtener cadena en formato YYYYMMDD desde el objeto de fecha JS?


Estoy tratando de usar JS para convertir un date object en una cadena en formato YYYYMMDD. ¿Hay una manera más fácil que concatenar Date.getYear(), Date.getMonth(), y Date.getDay()?

Author: Simpal Kumar, 2010-06-18

30 answers

Pieza de código alterada que uso a menudo:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();
 532
Author: o-o,
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-11-24 11:03:07

No me gustó añadir al prototipo. Una alternativa sería:

var rightNow = new Date();
var res = rightNow.toISOString().slice(0,10).replace(/-/g,"");

<!-- Next line is for code snippet output only -->
document.body.innerHTML += res;
 263
Author: Pierre Guilbert,
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-06-08 04:10:53

Puede usar la función toISOString:

var today = new Date();
today.toISOString().substring(0, 10);

Le dará un formato "aaaa-mm-dd".

 143
Author: Ramzi SAYAGH,
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-13 07:26:30

Momento.js podría ser tu amigo

var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
 100
Author: High6,
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-13 07:35:23

Si no necesita una solución JS pura, puede usar jQuery UI para hacer el trabajo de la siguiente manera:

$.datepicker.formatDate('yymmdd', new Date());

Normalmente no me gusta importar demasiadas bibliotecas. Pero la interfaz de usuario de jQuery es tan útil, que probablemente la usará en otro lugar de su proyecto.

Visita http://api.jqueryui.com/datepicker / para más ejemplos

 33
Author: NLemay,
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
2013-12-18 21:46:05

Esta es una sola línea de código que puede usar para crear una cadena YYYY-MM-DD de la fecha de hoy.

var d = new Date().toISOString().slice(0,10);
 31
Author: Brian Powell,
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-03-16 22:23:29

Además de la respuesta de o-o, me gustaría recomendar separar las operaciones lógicas del retorno y ponerlas como ternarios en las variables en su lugar.

También, use concat() para asegurar la concatenación segura de variables

 Date.prototype.yyyymmdd = function() {
   var yyyy = this.getFullYear();
   var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
   var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
   return "".concat(yyyy).concat(mm).concat(dd);
  };

 Date.prototype.yyyymmddhhmm = function() {
   var yyyy = this.getFullYear();
   var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
   var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
   var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
   var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
   return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min);
  };

 Date.prototype.yyyymmddhhmmss = function() {
   var yyyy = this.getFullYear();
   var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based
   var dd  = this.getDate() < 10 ? "0" + this.getDate() : this.getDate();
   var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
   var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
   var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
   return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min).concat(ss);
  };

var d = new Date();
d.yyyymmdd();
d.yyyymmddhhmm();
d.yyyymmddhhmmss();

Un violín un poco más SECO como sugiere RiZKiT

Https://jsfiddle.net/EricHerlitz/tuhhfxz9 /

 23
Author: Eric Herlitz,
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-01-23 11:41:04

No me gusta modificar objetos nativos, y creo que la multiplicación es más clara que la cadena de relleno de la solución aceptada.

function yyyymmdd(dateIn) {
   var yyyy = dateIn.getFullYear();
   var mm = dateIn.getMonth()+1; // getMonth() is zero-based
   var dd  = dateIn.getDate();
   return String(10000*yyyy + 100*mm + dd); // Leading zeros for mm and dd
}

var today = new Date();
console.log(yyyymmdd(today));

Violín: http://jsfiddle.net/gbdarren/Ew7Y4/

 16
Author: D-Money,
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-06-13 22:30:53
new Date('Jun 5 2016').
  toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
  replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');

// => '2016-06-05'
 16
Author: gongqj,
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-06-06 03:11:06

Solución simple JS (ES5) sin ningún posible problema de salto de fecha causado por Date.toISOString () imprimiendo en UTC:

var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');

Esto en respuesta al comentario de @weberste sobre la respuesta de @Pierre Guilbert.

 13
Author: Dormouse,
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-15 14:40:42

// UTC/GMT 0
document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509

// Client local time
document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509
 9
Author: Kus,
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-12 01:38:22

var someDate = new Date();
var dateFormated = someDate.toISOString().substr(0,10);

console.log(dateFormated);
 8
Author: Tomas Šivickas,
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-23 13:06:45

Versión un poco simplificada para la respuesta más popular en este hilo https://stackoverflow.com/a/3067896/5437379 :

function toYYYYMMDD(d) {
    var yyyy = d.getFullYear().toString();
    var mm = (d.getMonth() + 101).toString().slice(-2);
    var dd = (d.getDate() + 100).toString().slice(-2);
    return yyyy + mm + dd;
}
 5
Author: Hero Qu,
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:10:34

Este código es fijo a la respuesta de Pierre Guilbert:

(funciona incluso después de 10000 años)

YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")
 5
Author: anmml,
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-17 00:33:06

Simplemente puede usar este código de una línea para obtener la fecha en el año

var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
 5
Author: Muhammad Ahsan,
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-28 10:37:46

Este tipo aquí = > http://blog.stevenlevithan.com/archives/date-time-format escribió una función format() para el objeto Date de Javascript, por lo que se puede usar con formatos literales familiares.

Si necesitas formato de fecha completo en Javascript de tu app, úsalo. De lo contrario, si lo que quieres hacer es un one off, entonces concatenar getYear (), getMonth (), getDay() es probablemente más fácil.

 4
Author: Strelok,
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
2010-06-18 01:05:42

Otra forma es usar toLocaleDateString con una configuración regional que tiene un estándar de formato de fecha big-endian, como Suecia, Lituania, Hungría, Corea del Sur, ...:

date.toLocaleDateString('se')

Para eliminar los delimitadores (-) es solo cuestión de reemplazar los no dígitos:

console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );

Esto no tiene el error potencial que puede obtener con los formatos de fecha UTC: la fecha UTC puede ser de un día de descanso en comparación con la fecha en la zona horaria local.

 4
Author: trincot,
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-10-29 11:49:14

Parece que mootools proporciona Date().format (): http://mootools.net/docs/more/Native/Date

No estoy seguro de si vale la pena incluirlo solo para esta tarea en particular.

 3
Author: Oren_H,
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
2010-06-18 01:08:11

Trabajando desde la respuesta de @o-o, esto le devolverá la cadena de la fecha de acuerdo con una cadena de formato. Puede agregar fácilmente una expresión regular del año de 2 dígitos para el año y milisegundos y el tal si los necesita.

Date.prototype.getFromFormat = function(format) {
    var yyyy = this.getFullYear().toString();
    format = format.replace(/yyyy/g, yyyy)
    var mm = (this.getMonth()+1).toString(); 
    format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
    var dd  = this.getDate().toString();
    format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
    var hh = this.getHours().toString();
    format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
    var ii = this.getMinutes().toString();
    format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
    var ss  = this.getSeconds().toString();
    format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
    return format;
};

d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);

No se lo eficiente que es, sin embargo, especialmente en cuanto a perf, ya que utiliza una gran cantidad de expresiones regulares. Probablemente podría usar algún trabajo que no domine js puro.

 3
Author: Tom Toms,
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-25 21:12:58

Normalmente uso el código de abajo cuando necesito hacer esto.

var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
    + ('0' + (date.getMonth() + 1)).slice(-2)
    + '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written

Para explicar, .slice(-2) nos da los dos últimos caracteres de la cadena.

Así que no importa qué, podemos agregar "0" al día o mes, y simplemente preguntar por los dos últimos ya que esos son siempre los dos que queremos.

Así que si el myDate.getMonth () devuelve 9, será:

("0" + "9") // Giving us "09"

Así que la adición .slice(-2) en eso nos da los dos últimos caracteres que son:

("0" + "9").slice(-2)

"09"

Pero si fecha.getMonth () devuelve 10, lo hará be:

("0" + "10") // Giving us "010"

Así que la adición .slice (-2) nos da los dos últimos caracteres, o:

("0" + "10").slice(-2)

"10"
 3
Author: Ogglas,
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-09-18 13:23:56

Dateformat es muy utilizado el paquete y me parece mucho más robusto y fácil de usar que momento.js .

Modo de empleo:

Descargue e instale dateformat desde NPM. Requiéralo en tu módulo:

var dateFormat = require('dateformat');

Y luego simplemente formatea tus cosas:

var myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');

 3
Author: Milkncookiez,
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-04-25 09:48:41

Si usa AngularJS (hasta 1.5) puede usar el filtro de fecha :

var formattedDate = $filter('date')(myDate, 'yyyyMMdd')
 3
Author: sarin,
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-02 17:29:38

Si no te importa incluir una biblioteca adicional (pero pequeña), Sugar.js proporciona mucha funcionalidad para trabajar con fechas en JavaScript. Para dar formato a una fecha, utilice la función format :

new Date().format("{yyyy}{MM}{dd}")
 2
Author: andersh,
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-06-19 20:17:41

Respondiendo a otro por Simplicidad y legibilidad.
Además, no se recomienda editar los miembros de clase predefinidos existentes con nuevos métodos:

function getDateInYYYYMMDD() {
    let currentDate = new Date();

    // year
    let yyyy = '' + currentDate.getFullYear();

    // month
    let mm = ('0' + (currentDate.getMonth() + 1));  // prepend 0 // +1 is because Jan is 0
    mm = mm.substr(mm.length - 2);                  // take last 2 chars

    // day
    let dd = ('0' + currentDate.getDate());         // prepend 0
    dd = dd.substr(dd.length - 2);                  // take last 2 chars

    return yyyy + "" + mm + "" + dd;
}

var currentDateYYYYMMDD = getDateInYYYYMMDD();
console.log('currentDateYYYYMMDD: ' + currentDateYYYYMMDD);
 2
Author: Manohar Reddy Poreddy,
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-11-09 09:33:42

yyyymmdd=x=>(f=x=>(x<10&&'0')+x,x.getFullYear()+f(x.getMonth()+1)+f(x.getDate()));
alert(yyyymmdd(new Date));
 2
Author: Enam,
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-01-13 22:04:12

Date-shortcode al rescate!

const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYYMMDD}', new Date())
//=> '20180304'
 2
Author: Kodie Grantham,
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-04 18:49:55

Aquí hay un enfoque más genérico que permite ambos componentes date y time y es idénticamente clasificable como número o cadena.

Basado en el orden numérico del formato ISO de fecha, convierta a una zona horaria local y elimine los que no sean dígitos. es decir:

// monkey patch version
Date.prototype.IsoNum = function (n) {
    var tzoffset = this.getTimezoneOffset() * 60000; //offset in milliseconds
    var localISOTime = (new Date(this - tzoffset)).toISOString().slice(0,-1);
    return localISOTime.replace(/[-T:\.Z]/g, '').substring(0,n || 20); // YYYYMMDD
}

Uso

var d = new Date();
// Tue Jul 28 2015 15:02:53 GMT+0200 (W. Europe Daylight Time)
console.log(d.IsoNum(8));  // "20150728"
console.log(d.IsoNum(12)); // "201507281502"
console.log(d.IsoNum());   // "20150728150253272"
 1
Author: chriskelly,
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-09-26 12:33:32

Javascript nativo:

new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');
 1
Author: Lonnie Best,
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-11-14 21:20:35

Qué tal Día.js ?

Es solo 2KB, y también puedes dayjs().format('YYYY-MM-DD').

Https://github.com/iamkun/dayjs

 1
Author: NoobTW,
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-07-24 08:53:20

Aquí hay una pequeña mejora a la respuesta de https://stackoverflow.com/users/318563/o-o

Date.prototype.ddmmyyyy = function(delimiter) {
    var yyyy = this.getFullYear().toString();
    var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
    var dd  = this.getDate().toString();
    return (dd[1]?dd:"0"+dd[0]) + delimiter + (mm[1]?mm:"0"+mm[0]) + delimiter +yyyy  ; // padding
};

Espero ser de ayuda para cualquiera!

:)

 0
Author: Ismael Terreno,
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-03-05 19:00:15