Print only the last two digits of a year

Asked

Viewed 600 times

7

How to make the year have only two digits?

data = new Date().getFullYear();

console.log(data);

console.log(data.substr(2,4));

2 answers

8

Like the return of getFullYear() is a number, can’t use substr (for this method exists only for strings).

In this case, you can take the rest of the division by 100:

let ano = new Date().getFullYear();

console.log(ano % 100); // 19


If the year is 2003, for example, then a little more work is needed, as the result will be 3 and will not be printed with zero left.

You can use padStart to put the zero in front (and in that case you will need to convert to string first, using toString()), or make a more "manual" process to add zero:

// alternativa 1: usar padStart
let ano = 2003;
console.log((ano % 100).toString().padStart(2, 0)); // 03

// alternativa 2: calcular o resto da divisão e adicionar o zero manualmente
ano = ano % 100;
console.log(`${ano < 10 ? '0' : ''}${ano}`); // 03


There is still another alternative, using the method toLocaleString. In this case, just specify the minimum number of digits you want to display, the remainder is filled with zeros on the left:

let ano = 2003;
console.log((ano % 100).toLocaleString('pt', { minimumIntegerDigits: 2 })); // 03

ano = 2019;
console.log((ano % 100).toLocaleString('pt', { minimumIntegerDigits: 2 })); // 19

The parameter 'pt' refers to the locale (in this case, "pt" is the code for "Portuguese"), and influences some details in the output format (such as using the dot or comma to separate the thousands or decimals, if you use the locale in Portuguese or English, for example). But in this particular case, since the values are less than 1000 and there are no decimals, it doesn’t make that much difference. What is important in this case is the value of minimumIntegerDigits.

  • Now just in case the year is 2103... rs

  • @Sam Code Future Proof, Better safe than sorry :-)

8

We convert to string, then take only the last two characters:

data = new Date().getFullYear().toString().substr(-2);
console.log(data);

Browser other questions tagged

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