Categories
JavaScript Answers

How to Calculate the Day of the Year with JavaScript?

Spread the love

We can calculate the day of the year with JavaScript with some native date methods.

For instance, we can write:

const now = new Date(2021, 11, 3);
const start = new Date(2021, 0, 0);
const diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
console.log(day);

We have the now and start date where now is the date we want to calculate the difference from start .

Then we calculate the diff difference by subtract now from start and add the time zone offsets differences to correct discrepancies because of time zone differences.

Next, we calculate the number of milliseconds in a day with the oneDay variable.

Next, we calculate the number of days difference between now and start by dividing diff with oneDay and then take the floor of the quotient with Math.floor .

And then we log the day result.

day should be 337 according to the console log.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *