getMonth()
returns a number. If you want a string, create another variable to receive the properly formatted value:
const today = new Date();
const mes = today.getMonth() + 1;
let todayMonth;
if (mes < 10) {
todayMonth = '0' + mes;
} else {
todayMonth = mes.toString();
}
You can also enable ES2017 (switching to target: "es2017"
in his tsconfig
), so it will be possible to use padStart
, which already fills with that zero left if necessary:
const today = new Date();
let todayMonth = (today.getMonth() + 1).toString().padStart(2, 0);
There are other answers suggesting using toLocaleDateString
or toISOString
, which also work (although I find it an exaggeration to format the date for a string just to do several split
's, being that - in my opinion - it is much simpler to get the month directly with getMonth()
and format it the way you think best).
But there is another fundamental difference: toLocaleDateString
returns the value of the month according to the browser’s Timezone (or whatever is configured in Node), which is consistent with getMonth()
. Already toISOString
returns the month according to the date on UTC, which may not always be the same browser Timezone month (and is consistent with getUTCMonth()
). For example, in my browser the Timezone configured is the Brasilia Time (in this case, Chrome uses the operating system), so see what happens to the code below:
let d = new Date(2019, 5, 30, 23, 0); // 30 de junho de 2019, às 23:00
// resultados obtidos em um browser cujo fuso é o Horário de Brasília
console.log(d.toLocaleDateString('pt-BR')); // 30/06/2019
console.log(d.toISOString()); // 2019-07-01T02:00:00.000Z
console.log(d.getMonth() + 1); // 6
console.log(d.getUTCMonth() + 1); // 7
If your browser is set to a different time zone, the results may vary.
The date created corresponds to 30 June 2019, at 23:00, in the browser Timezone (in my case, Time Brasilia), then toLocaleDateString
returns 30/06/2019
. Already toISOString
returns this same date in UTC (and 30 June 2019, at 23:00 in the Time of Brasilia corresponds to July 1 from 2019 to 02:00 UTC), so in this case the month is 07
. Of course there will not always be this difference (for most of the time, the local month is the same as the month in UTC), but depending on what you are doing, it is important to decide whether you will use UTC or the browser Timezone.
Anyway, you don’t need to turn the date into a string and do split
. If you want the month according to the browser Timezone, use getMonth()
, but if you want the UTC value, use getUTCMonth()
- and for both, use one of the options already indicated above (if (valor < 10) etc..
or padStart
).
In both jsx, typescript or javascript, it is the same procedure.
– Ivan Ferrer