Get week from date through script in servicenow

Neeraja2
Tera Contributor

Hello Everyone,

I need to get week from a date in a month. Not in a year.

For example, 

for example : if date is 2024-02-05

The output should be :

week - 1st week (as it is 1st week of February and not year)

 

Please anyone suggest script on this? Thanks in advance

10 REPLIES 10

This isn't the best code example, but this gets the job done.

Use it if you like.

 

var date = '2024-02-05';
var gdt = new GlideDateTime(date);

if (gdt.isValid()){
    var dayMonth = gdt.getDayOfMonthUTC();

    if (dayMonth<=7){
        gs.info('1st week');
    }
    else if (dayMonth>7 && dayMonth<=14){
        gs.info('2nd week');
    }
    else if (dayMonth>14 && dayMonth<=21){
        gs.info('3rd week');
    }
    else if (dayMonth>21 && dayMonth<=28){
        gs.info('4th week');
    }
    else if (dayMonth>28 && dayMonth<=35){
        gs.info('5th week');
    }
}
else{
    gs.info('Invalid date');
}

anshul_goyal
Kilo Sage

Hello @Neeraja2,

Please use the OOTB method to fetch the weeks in a particular year. Below is the method: 

var gdt = new GlideDateTime("mention_date");
gs.info("Week- " + gdt.getDayOfWeekLocalTime());

Please mark my answer as helpful and accepted.

Thanks,
Anshul

Peter Bodelier
Giga Sage

Hi @Neeraja2,

 

Very basically this should work. 

var dt = new GlideDate();
var date = dt.getDayOfMonth();
var day = dt.getDayOfWeek()
var weekOfMonth = Math.ceil((date - 1 - day) / 7);

 

This would return the first week of the month as 0.

It's not exactly according to your example, since the 1st and 5th are in different weeks in February 2024, but I think that is actually correct.


Help others to find a correct solution by marking the appropriate response as accepted solution and helpful.

Amit Verma
Kilo Patron
Kilo Patron

Hi @Neeraja2 

 

Please check if below code helps :

 

var prefixes = ['First', 'Second', 'Third', 'Fourth', 'Fifth'];
var gdt = new GlideDateTime();
var day=gdt.getDayOfMonthLocalTime();
gs.log('This is '+prefixes[0 | day / 7]+' Week of Month');

 

Thanks & Regards

Amit Verma


Please mark this response as correct and helpful if it assisted you with your question.

SunilKumar_P
Giga Sage

Hi @Neeraja2, can you try the below script?

 

var gdt = new GlideDateTime("17-01-2024");
gs.info(gdt.getWeekOfYearLocalTime());

 

SunilKumar_P_0-1707210409993.png

 

Regards,

Sunil

 

Kindly mark my response as helpful and correct if it assited you.