Sometimes, we want to calculate the day of the year with JavaScript.

In this article, we’ll look at how to calculate the day of the year with JavaScript.

### How to calculate the day of the year with JavaScript?

To calculate the day of the year with JavaScript, we can calculate the difference between the current datetime and the midnight of the first day of the year.

For instance, we write

```
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff =
now -
start +
(start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000;
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
```

to calculate `diff`

by subtracting `now`

by `start`

.

And then we add back the time zone offset difference to add back the difference caused by daylight saving time.

Then we divide `diff`

by `oneDay`

, which is 1 day in milliseconds.

Finally, we call `Math.floor`

to round the quotient down.

### Conclusion

To calculate the day of the year with JavaScript, we can calculate the difference between the current datetime and the midnight of the first day of the year.