Come posso ottenere il mese e la data di JavaScript in formato a 2 cifre?


Risposte:


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

per la data e simili:

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

per il mese.


86
Fantastico, ma: function addZ(n){return n<10? '0'+n:''+n;}è un po 'più generico.
RobG,

9
slice è intelligente, ma è molto più lento di un semplice confronto: jsperf.com/slice-vs-comparison
dak,

30
@dak: E quando ciò avrà realisticamente importanza? Dubito che tu stia calcolando il mese migliaia di volte al secondo.
Sasha Chedygov,

2
@ KasperHoldum– getMonthe getDaterestituisce numeri, non stringhe. E se è richiesta la compatibilità con le stringhe, allora '0' + Number(n)farà il lavoro.
RobG

9
@Sasha Chedygov sicuramente potresti calcolare il mese migliaia di volte al secondo, in particolare se stai ordinando
Dexygen

87

Se desideri un formato come "AAAA-MM-GGTHH: mm: ss", potrebbe essere più veloce:

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

O il formato datetime MySQL comunemente usato "AAAA-MM-GG HH: mm: ss":

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

Spero che aiuti


1
Questa è la soluzione più difficile che abbia mai incontrato. L'unico problema qui è quello della differenza di fuso orario.
Praym,

3
L'offset del fuso orario può essere curato con qualcosa del tipo: var date = new Date (new Date (). GetTime () - new Date (). GetTimezoneOffset () * 60 * 1000) .toISOString (). Substr (0,19) .replace ('T', '');
Praym,

Praym, il tuo codice funziona per me, ma copia e incolla deve aver avuto qualche carattere nascosto o qualcosa del genere, quindi l'ho appena scritto a mano.
spacebread

Ho finito con questa domanda cercando di risolvere esattamente questo problema, quindi, a quanto pare, la tua risposta è ciò di cui avevo bisogno.
Ingegnere Toast,

Si noti che questo metodo restituirà la data e l'ora in base al fuso orario UTC.
Amr

41

Esempio per mese:

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

È inoltre possibile estendere l' Dateoggetto con tale funzione:

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

4
Nota che getMonth restituisce un numero compreso tra 0 e 11, non 1 e 12.
Salman A

4
Ciò restituisce risultati incoerenti. Per novembre e dicembre restituisce una stringa e per altri mesi restituisce un numero.
Tim Down,

Ho aggiornato il codice per implementare Salman Un avvertimento che getMonth è basato su zero invece di 1. E ho aggiunto virgolette per assicurarsi che venga sempre restituita una stringa.
Jan Derk,

23

Il modo migliore per farlo è creare il tuo semplice formatter (come sotto):

getDate()restituisce il giorno del mese (da 1-31)
getMonth()restituisce il mese (da 0-11) < a base zero, 0 = gennaio, 11 = dicembre
getFullYear() restituisce l'anno (quattro cifre) < non utilizzaregetYear()

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

Perché non usare 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);

Ciò restituirà sempre numeri a 2 cifre anche se il mese o il giorno è inferiore a 10.

Appunti:

  • Funzionerà con Internet Explorer solo se il codice js viene compilato usando babel .
  • getYear()restituisce l'anno dal 1900 e non richiede padStart.
  • getMonth() restituisce il mese da 0 a 11.
    • 1 viene aggiunto al mese prima dell'imbottitura per mantenerlo da 1 a 12
  • getDate() ritorna il giorno da 1 a 31.
    • il settimo giorno tornerà 07e quindi non è necessario aggiungere 1 prima di riempire la stringa.

1
Sì. È incluso nel link MDN sopra. Se usi babel per traspilare, non dovresti avere problemi.
SomeGuyOnAComputer

10

Quanto segue viene utilizzato per convertire il formato data db2, ovvero AAAA-MM-GG, utilizzando l'operatore 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

Vorrei fare questo:

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 un altro esempio, quasi una fodera.

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

Se potesse risparmiare un po 'di tempo stavo cercando di ottenere:

YYYYMMDD

per oggi, e andava d'accordo con:

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

2
La risposta è chiara Per DD/MM/YY, sono andato anew Date().toISOString().substr(0, 10).split('-').reverse().map(x => x.substr(0, 2)).join('/')
Max Ma

4

Questa era la mia soluzione:

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

Non è una risposta, ma ecco come ottengo il formato data richiesto in una variabile

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);

Spero che questo ti aiuti!


2

Suggerimento da 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() Il metodo restituisce il mese come un numero (0-11)

È possibile ottenere facilmente il numero del mese corretto con questa funzione.

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

E un'altra versione qui https://jsfiddle.net/ivos/zcLxo8oy/1/ , spero di essere utile.

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

Le risposte qui sono state utili, tuttavia ho bisogno di più di questo: non solo mese, data, mese, ore e secondi, per un nome predefinito.

È interessante notare che sebbene fosse necessario anteporre "0" per tutto quanto sopra, "+ 1" era necessario solo per il mese, non per altri.

Per esempio:

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

0

La mia soluzione:

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

se vuoi che la funzione getDate () restituisca la data come 01 anziché 1, ecco il codice per essa .... Supponiamo che la data di oggi sia 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

Volevo fare qualcosa del genere e questo è quello che ho fatto

ps so che ci sono risposte giuste in alto, ma volevo solo aggiungere qualcosa di mio qui

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;
}

troppo sforzo. No?
ahmednawazbutt,

0

Se controlli meno di 10 , non devi creare una nuova funzione per quello. Basta assegnare una variabile tra parentesi e restituirla con un operatore 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

Suggerirei di utilizzare una libreria diversa chiamata Moment https://momentjs.com/

In questo modo sei in grado di formattare la data direttamente senza dover fare un lavoro extra

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

Assicurati di importare anche il momento per poterlo usare.

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

Spero che questo aiuti: D


1
Moment.js è già stato suggerito; ma il tuo consiglio è ancora completo e utile.
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);
});
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.