Calculate days between two dates in portal

Sowmya20
Tera Contributor

Hi,

 

I have requirement to display number of days between two dates in portal.

Example: Start Date :28-08-2023

                End Date: 30-08-2023

No.of Days need display: 3

Sowmya20_0-1692961979525.png

Please help.

Thanks,

Sowmya

11 REPLIES 11

Hi @Sowmya20 ,

use below script

1. create onchange catalog client script on end date and UI type should be all

function onChange(control, oldValue, newValue, isLoading) {
	if (isLoading || newValue == '') {
		return;
	}
	var ga=new GlideAjax('GetDays');//script include name
	ga.addParam('sysparm_name','getNoofDays');//function name
	ga.addParam('sysparm_start_date',g_form.getValue('start_date'));//passing start date to server
	ga.addParam('sysparm_end_Date',newValue);
	ga.getXMLAnswer(setDays);
	function setDays(response){
		var daysdiff=parseInt(response)+1; //covert to int and add 1 
		g_form.setValue('no_of_days', daysdiff); //add your variable name
	}
}

Refer below

Screenshot (52).png

2. Create Script include and check client callable

var GetDays = Class.create();
GetDays.prototype = Object.extendsObject(AbstractAjaxProcessor, {
	getNoofDays: function() {
		var start = this.getParameter('sysparm_start_date'); //Passing the start date from the client
		var end = this.getParameter('sysparm_end_Date'); //Passing the end date from the client
		
		var startDate = new GlideDateTime(start);
		var endDate =new GlideDateTime(end);
		var duration1 = gs.dateDiff(startDate.getDisplayValue(), endDate.getDisplayValue(), true);
		var days=duration1/86400;
		
		return days;
	},
	type: 'GetDays'
});

Refer below

Screenshot (53).png

Result:

Screenshot (54).png

If it helps please click Accept as Solution/hit the Thumb Icon.
ServiceNow Community MVP 2024.
Thanks,
Pavankumar

Pavankumar_1
Mega Patron

Hi @Sowmya20 ,

If your got the resolved then close question by Accepting the solution then only this post will be useful for other users.

If it helps please click Accept as Solution/hit the Thumb Icon.
ServiceNow Community MVP 2024.
Thanks,
Pavankumar