Let's now learn how to display the date in a specific format. Let, for example, we want to display the current day, month and year in the format year-month-day.
Let's do that:
let date = new Date();
console.log(date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate());
Our code, however, has a problem: the month numbers will start with a zero, and we would most likely want them to start with a one.
Let's fix the problem:
let date = new Date();
console.log(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
Our code, however, is still not perfect. But
you can notice this only in certain months
and on certain days. Let, for example, it
is now 5
th of March 2020
.
In this case, our date will be displayed in the format 2020-3-5. And we would like the date to be displayed in the format 2020-03-05 - with zeros before the numbers of days and months with one digit.
To solve the problem, let's write the function
addZero
, which will add zeros in front
of numbers from 0
to 9
:
function addZero(num) {
if (num >= 0 && num <= 9) {
return '0' + num;
} else {
return num;
}
}
Let's apply the created function and now we will actually get the date in the format we need:
let date = new Date();
console.log(
addZero(date.getFullYear()) + '-' +
addZero(date.getMonth() + 1) + '-' +
addZero(date.getDate())
);
Display the current date-time in the format 12:59:59 31.12.2014. Use for all parts of the date (except for the year) the function we created to add a zero if necessary.