¿Cómo obtengo el mes y la fecha de JavaScript en formato de 2 dígitos?


Respuestas:


812
("0" + this.getDate()).slice(-2)

para la fecha y similares:

("0" + (this.getMonth() + 1)).slice(-2)

por el mes.


86
Genial, pero: function addZ(n){return n<10? '0'+n:''+n;}es un poco más genérico.
— RobG

99
el segmento es inteligente, pero es mucho más lento que una simple comparación: jsperf.com/slice-vs-comparison
— dak

30
@dak: ¿Y cuándo va a importar eso de manera realista? Dudo que estés calculando el mes miles de veces por segundo.
— Sasha Chedygov

2
@ KasperHoldum– getMonthy getDatedevolver números, no cadenas. Y si se requiere compatibilidad con Strings, entonces '0' + Number(n)hará el trabajo.
— RobG

99
@Sasha Chedygov seguro que puede calcular el mes miles de veces por segundo, especialmente si está ordenando
— Dexygen

87

Si desea un formato como "AAAA-MM-DDTHH: mm: ss", entonces esto podría ser más rápido:

var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ

O el formato de fecha y hora de MySQL comúnmente utilizado "AAAA-MM-DD HH: mm: ss":

var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');

espero que esto ayude


1
Esta es la mejor solución que he encontrado. El único problema aquí es el del desplazamiento de la zona horaria.
— Praym

3
El desplazamiento de la zona horaria podría solucionarse con algo como: var date = new Date (new Date (). GetTime () - new Date (). GetTimezoneOffset () * 60 * 1000) .toISOString (). Substr (0,19) .replace ('T', '');
— Praym

Praym, su código funciona para mí, pero copiar y pegar debe haber tenido algún carácter oculto o algo así que lo escribí a mano.
— spacebread

Terminé con esta pregunta tratando de resolver este problema exacto, así que, como resultado, su respuesta es lo que necesitaba.
— Engineer Toast

Tenga en cuenta que este método devolverá la fecha y la hora de acuerdo con la zona horaria UTC.
— Amr

41

Ejemplo por mes:

function getMonth(date) {
  var month = date.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}  

También puede extender Dateobjetos con dicha función:

Date.prototype.getMonthFormatted = function() {
  var month = this.getMonth() + 1;
  return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}

44
Tenga en cuenta que getMonth devuelve un número entre 0 y 11, no 1 y 12.
— Salman A

44
Esto devuelve resultados inconsistentes. Para noviembre y diciembre devuelve una cadena y para otros meses devuelve un número.
— Tim Down

Actualicé el código para implementar Salman Una advertencia de que getMonth está basado en cero en lugar de 1. Y agregué comillas para asegurarme de que siempre se devuelva una cadena.
— Jan Derk

23

La mejor manera de hacer esto es crear su propio formateador simple (como se muestra a continuación):

getDate()devuelve el día del mes (del 1 al 31)
getMonth()devuelve el mes (del 0 al 11) < basado en cero, 0 = enero, 11 = diciembre
getFullYear() devuelve el año (cuatro dígitos) < no usargetYear()

function formatDateToString(date){
   // 01, 02, 03, ... 29, 30, 31
   var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
   // 01, 02, 03, ... 10, 11, 12
   var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
   // 1970, 1971, ... 2015, 2016, ...
   var yyyy = date.getFullYear();

   // create the format you want
   return (dd + "-" + MM + "-" + yyyy);
}

20

¿Por qué no usar padStart?

var dt = new Date();

year  = dt.getYear() + 1900;
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day   = dt.getDate().toString().padStart(2, "0");

console.log(year + '/' + month + '/' + day);

Esto siempre devolverá números de 2 dígitos, incluso si el mes o el día es inferior a 10.

Notas:

  • Esto solo funcionará con Internet Explorer si el código js se transpira usando babel .
  • getYear()Regresa el año de 1900 y no requiere padStart.
  • getMonth() devuelve el mes de 0 a 11.
    • 1 se agrega al mes antes del relleno para mantenerlo de 1 a 12
  • getDate() devuelve el día del 1 al 31.
    • el séptimo día volverá 07y, por lo tanto, no necesitamos agregar 1 antes de rellenar la cadena.

1
Sip. Está incluido en el enlace de MDN anterior. Si usa babel para transpilar, no debería tener ningún problema.
— SomeGuyOnAComputer

10

Lo siguiente se usa para convertir el formato de fecha db2, es decir, AAAA-MM-DD usando el operador ternario

var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);  
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate; 
alert(createdDateTo);

7

Yo haría esto:

var d = new Date('January 13, 2000');
var s = d.toLocaleDateString('en-US', { month: '2-digit', day: '2-digit', year: 'numeric' });
console.log(s); // prints 01/13/2000


6
function monthFormated(date) {
   //If date is not passed, get current date
   if(!date)
     date = new Date();

     month = date.getMonth();

    // if month 2 digits (9+1 = 10) don't add 0 in front 
    return month < 9 ? "0" + (month+1) : month+1;
}

6

Solo otro ejemplo, casi un revestimiento.

var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );


5
function monthFormated() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

5

Si me permitiera algo de tiempo, estaba buscando:

YYYYMMDD

por hoy, y me llevé bien con:

const dateDocumentID = new Date()
  .toISOString()
  .substr(0, 10)
  .replace(/-/g, '');

2
La respuesta es ordenada. Para DD/MM/YY, fui anew Date().toISOString().substr(0, 10).split('-').reverse().map(x => x.substr(0, 2)).join('/')
— Max Ma

4

Esta fue mi solución:

function leadingZero(value) {
  if (value < 10) {
    return "0" + value.toString();
  }
  return value.toString();
}

var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;


3

No es una respuesta, pero así es como obtengo el formato de fecha que requiero en una variable

function setDateZero(date){
  return date < 10 ? '0' + date : date;
}

var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);

¡Espero que esto ayude!


2

Consejo de MDN :

function date_locale(thisDate, locale) {
  if (locale == undefined)
    locale = 'fr-FR';
  // set your default country above (yes, I'm french !)
  // then the default format is "dd/mm/YYY"

  if (thisDate == undefined) {
    var d = new Date();
  } else {
    var d = new Date(thisDate);
  }
  return d.toLocaleDateString(locale);
}

var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);

http://jsfiddle.net/v4qcf5x6/


2

new Date().getMonth() El método devuelve el mes como un número (0-11)

Puede obtener fácilmente el número de mes correcto con esta función.

function monthFormatted() {
  var date = new Date(),
      month = date.getMonth();
  return month+1 < 10 ? ("0" + month) : month;
}

1
function GetDateAndTime(dt) {
  var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());

  for(var i=0;i<arr.length;i++) {
    if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
  }

  return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5]; 
}

1

Y otra versión aquí https://jsfiddle.net/ivos/zcLxo8oy/1/ , espero sea de utilidad.

var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup

strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")

1

Las respuestas aquí fueron útiles, sin embargo, necesito más que eso: no solo mes, fecha, mes, horas y segundos, para un nombre predeterminado.

Curiosamente, aunque el antecedente de "0" era necesario para todo lo anterior, "+ 1" era necesario solo durante un mes, no otros.

Como ejemplo:

("0" + (d.getMonth() + 1)).slice(-2)     // Note: +1 is needed
("0" + (d.getHours())).slice(-2)         // Note: +1 is not needed

0

Mi solución:

function addLeadingChars(string, nrOfChars, leadingChar) {
    string = string + '';
    return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}

Uso:

var
    date = new Date(),
    month = addLeadingChars(date.getMonth() + 1),
    day = addLeadingChars(date.getDate());

jsfiddle: http://jsfiddle.net/8xy4Q/1/


0
var net = require('net')

function zeroFill(i) {
  return (i < 10 ? '0' : '') + i
}

function now () {
  var d = new Date()
  return d.getFullYear() + '-'
    + zeroFill(d.getMonth() + 1) + '-'
    + zeroFill(d.getDate()) + ' '
    + zeroFill(d.getHours()) + ':'
    + zeroFill(d.getMinutes())
}

var server = net.createServer(function (socket) {
  socket.end(now() + '\n')
})

server.listen(Number(process.argv[2]))

0

si desea que la función getDate () devuelva la fecha como 01 en lugar de 1, aquí está el código para ello ... Supongamos que la fecha de hoy es 01-11-2018

var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();      
console.log(today);       //Output: 2018-11-1


today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today);        //Output: 2018-11-01

0

Quería hacer algo como esto y esto es lo que hice

PD: sé que hay respuestas correctas en la parte superior, pero solo quería agregar algo propio aquí

const todayIs = async () =>{
    const now = new Date();
    var today = now.getFullYear()+'-';
    if(now.getMonth() < 10)
        today += '0'+now.getMonth()+'-';
    else
        today += now.getMonth()+'-';
    if(now.getDay() < 10)
        today += '0'+now.getDay();
    else
        today += now.getDay();
    return today;
}

demasiado esfuerzo. ¿No es así?
— ahmednawazbutt

0

Si marca menos de 10 , no tiene que crear una nueva función para eso. Simplemente asigne una variable entre paréntesis y devuélvala con el operador ternario.

(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`

0
currentDate(){
        var today = new Date();
        var dateTime =  today.getFullYear()+'-'+
                        ((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
                        (today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
                        (today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
                        (today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
                        (today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());        
            return dateTime;
},

0

Te sugiero que uses una biblioteca diferente llamada Moment https://momentjs.com/

De esta manera, puede formatear la fecha directamente sin tener que hacer un trabajo adicional

const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'

Asegúrate de importar el momento también para poder usarlo.

yarn add moment 
# to add the dependency
import moment from 'moment' 
// import this at the top of the file you want to use it in

Espero que esto ayude: D


1
Moment.js ya ha sido sugerido; pero tu consejo sigue siendo completo y útil.
— iND

0
$("body").delegate("select[name='package_title']", "change", function() {

    var price = $(this).find(':selected').attr('data-price');
    var dadaday = $(this).find(':selected').attr('data-days');
    var today = new Date();
    var endDate = new Date();
    endDate.setDate(today.getDate()+parseInt(dadaday));
    var day = ("0" + endDate.getDate()).slice(-2)
    var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
    var year = endDate.getFullYear();

    var someFormattedDate = year+'-'+month+'-'+day;

    $('#price_id').val(price);
    $('#date_id').val(someFormattedDate);
});
Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.