I need a JavaScript-function which always computes the date of the next day. Then returns the date as a string, formatted in the way: dd.mm.yyyy
I wrote this code:
const getDateStringForTomorrow = () => {
const millisOfDay = 1000 * 60 * 60 * 24;
const oTomorrow = new Date(Date.now() + millisOfDay);
const day = ("0" + oTomorrow.getDate()).slice(-2);
const month = ("0" + (oTomorrow.getMonth() + 1)).slice(-2);
const year = oTomorrow.getFullYear();
return `${day}.${month}.${year}`;
};
console.log(getDateStringForTomorrow());
Can I expect my function to work as expected and to provide correct results?
What't your opinion about the way I have written the function? To you think it's overly verbose?
1 Answer 1
With Intl.DateTimeFormat you can also format the date elements to 2 and 4 digits. You code would then look something like this:
const getDateStringForTomorrow = () => {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
const day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(tomorrow);
const month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(tomorrow);
const year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(tomorrow);
return day + '.' + month + '.' + year;
};
console.log(getDateStringForTomorrow());
Another variant uses the European date format to get the order of the elements correctly and then only replaces dashes by dots:
const getDateStringForTomorrow = () => {
const tomorrowDate = new Date();
tomorrowDate.setDate(tomorrowDate.getDate() + 1);
const tomorrowStr = new Intl.DateTimeFormat('uk', { day: '2-digit', month: '2-digit', year: 'numeric' }).format(tomorrow);
return tomorrowStr.replaceAll('-','.');
};
console.log(getDateStringForTomorrow());
The advantage of using Intl.DateTimeFormat()
is that it writes out very clearly what you want.
.toString().padStart(2, '0')
- I think it reads a little better. \$\endgroup\$oTomorrow = new Date(); oTomorrow.setDate(oTomorrow.getDate() + 1)
(setDate() will correctly handle too-large numbers) \$\endgroup\$