How to get the month formatted with zero left in Typescript

Asked

Viewed 729 times

6

I’m trying to get the month in Typescript with Node.js, I’m trying to get it like this:

const today = new Date();
var todayMonth = today.getMonth() + 1
if(todayMonth < 10) {
  todayMonth = '0' + todayMonth
}

But I’m getting the following error:

"String type cannot be assigned to type number. ts(2322)."

How could I make to validate if the month is less than 10 put the 0 in front to stay like month 01, 02, 03, etc..?

  • In both jsx, typescript or javascript, it is the same procedure.

4 answers

8

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

2

Just create a variable just for that, Typescript is not Javascript, each variable has a type of can not change, IE Typescript is not messy:

let month = new Date().getMonth() + 1;
let todayMonth = month.toString();
if (todayMonth < 10) todayMonth = '0' + month.toString();

I put in the Github for future reference.

2

I believe you’ll have your month with zero:

(new Date('Jan 05 2019'))
.toLocaleDateString('pt-BR')
.split('/')[1];

You can also get the month of a formatted date from the return in string, in ISO format:

var dt = new Date('2019-01-10');
console.log(dt.toISOString().split('T')[0].split('-')[1]);

Both ways, allow you to receive a date originally in Brazilian format, so you wouldn’t necessarily need to add zero when it was less than 10, since javascript is already bringing in the Brazilian format you need, I just profiled the result in the cases up, if you leave the .toLocaleDateString()empty, it will use the default of the user’s browser, from where it is.

2

That’s how it works too

mes = new Date().toISOString().split('T')[0].split('-')[1];

Basically in a step-by-step explanation:

  1. new date(); => returns a Date object that contains current date along with the time;
  2. .toISOString() => returns the date in the standard example '2019-11-05T13:31:22.753Z', the return is a string type
  3. .split(’T')[0] => will split the string by cutting it where the T, only the first part of the cut interest returning '2019-11-05'
  4. split('-')[1] => will divide the string '2019-11-05' by - so only the second occurrence matters, because this is the month
  5. return is '11' of type String

Same code works for specific dates

data = '2050-04-21T03:00:00.000Z'; // data no formato ISO
mes = new Date(data).toISOString().split('T')[0].split('-')[1]; // retorna 04
// ou mes = data.split('T')[0].split('-')[1]; 

let mesAtual = new Date().toISOString().split('T')[0].split('-')[1];
let mesDestaData = new Date('2050-04-21T03:00:00.000Z').toISOString().split('T')[0].split('-')[1];

console.log(mesAtual);
console.log(mesDestaData);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.