How to calculate the day of the year

JPSS
Tera Contributor

How to calculate the day of the year

 

 

like 

 

 

Today Tuesday October 24, 2023 is ...
Day 297

 

10 REPLIES 10

Niklas Peterson
Mega Sage

Hi,

Here is one way to do it. Take the difference between the day and the first day of the year and add one day.

var sgd1 = new GlideDate(); 
sgd1.setDisplayValue('2023-01-01'); 
var sgd2 = new GlideDate(); 
sgd2.setDisplayValue('2023-10-24'); 
 
var duration = GlideDate.subtract(sgd1, sgd2);
var dayNumber = parseInt(duration.getDisplayValue())+ 1;
 
gs.info(dayNumber);

 

Regards,
Niklas

This code works. But i need to have the year changed dynamically,Instead of hard coding

Sai Kumar P
Tera Guru
Tera Guru

Try this piece of code:

var currentDate = new Date();
// calculate the day of the year
var startOfYear = new Date(currentDate.getFullYear(), 0, 0);
var dayOfYear = Math.floor((currentDate - startOfYear) / 86400000);
gs.info("Today is Day " + (dayOfYear + 1));

OUTPUT:: 
*** Script: Today is Day 297



JPSS
Tera Contributor

with GlideDateTime can we achive this instead of date