2
\$\begingroup\$

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?

\$\endgroup\$
3
  • \$\begingroup\$ Instead of adding a '0' and slicing, I might prefer .toString().padStart(2, '0') - I think it reads a little better. \$\endgroup\$ – Scotty Jamison Dec 18 '20 at 8:03
  • 1
    \$\begingroup\$ Also, if accuracy matters, a day doesn't always have the same number of milliseconds (i.e. leap minutes). This would be an alternative way to get the next day: oTomorrow = new Date(); oTomorrow.setDate(oTomorrow.getDate() + 1) (setDate() will correctly handle too-large numbers) \$\endgroup\$ – Scotty Jamison Dec 18 '20 at 8:08
  • 1
    \$\begingroup\$ @Scotty Jamison I have seen the technique you are mentioning, in an article: flaviocopes.com/how-to-get-tomorrow-date-javascript Now, it becomes clear to me, why they are doing it that way. Thanks. \$\endgroup\$ – michael.zech Dec 18 '20 at 8:14
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.