Need to Get the day based on entered date & time

is_12
Tera Contributor

Hi Community,

 

On the Catalog form I have field start & end date.

 

Based on the start date need to get the day

 And also based on the start date, need to get the next 3months & 6months & 12months date

 

Can anyone help me with this

 

Thanks,

 

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@is_12 

try this and it will take care of any date/time format

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

    // Parse string to milliseconds
    var dateMS = getDateFromFormat(newValue, g_user_date_time_format);
    var newDT = new Date();
    newDT.setTime(dateMS);

    // Example: Add 3 months
    newDT.setMonth(newDT.getMonth() + 3);

    // If you want 6 or 12 months, just change the +3:
    // newDT.setMonth(newDT.getMonth() + 6); // For 6 months
    // newDT.setMonth(newDT.getMonth() + 12); // For 12 months

    var val = formatDate(newDT, g_user_date_time_format);
    alert(val);
}

Output:I added 3 months, enhance further

AnkurBawiskar_1-1761291386161.png

 

💡 If my response helped, please mark it as correct and close the thread 🔒— this helps future readers find the solution faster! 🙏

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

17 REPLIES 17

@is_12 

didn't get the requirement.

you need to add the value 21 (value in earlier variable) to the date entered by user?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Ankur Bawiskar 

Let me explain you
Let say user has selected the start date as today(25th) & day of the month as 28(28 is nothing but date) & select month as Every month
then day1 should be from day of month ie 28th +1 rather than start date+1
similarly let say select month is quatarely then it should be 28th +3

 

Thanks

MaxMixali
Giga Guru

ServiceNow – Catalog item: derive Day of Week and +3/+6/+12 month dates from Start Date

What you want
- On a catalog form, when the user selects Start Date:
1) Show the Day of Week for that date
2) Auto-populate dates at +3 months, +6 months, and +12 months

Approach (robust & timezone-safe)
Use an onChange Catalog Client Script that calls a Client‑callable Script Include. The server computes dates with GlideDateTime (handles locale/DST correctly), and returns a small JSON payload for the client to set variables.

Variables (example names)
- start_date (Type: Date)
- day_of_week (Type: Single Line Text, Read‑only = true)
- date_plus_3m (Type: Date, Read‑only = true)
- date_plus_6m (Type: Date, Read‑only = true)
- date_plus_12m (Type: Date, Read‑only = true)

1) Script Include (Client callable)
----------------------------------
Name: DateCalcAjax (global or your scope)
Client callable: ✔

/** Script Include **/
var DateCalcAjax = Class.create();
DateCalcAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getOffsets: function() {
var start = this.getParameter('sysparm_start'); // expects display or ISO date (yyyy-MM-dd)
if (!start) return '{}';

// Initialize
var gdt = new GlideDateTime();
// If start is just a date (no time), set to local 00:00
gdt.setDisplayValue(start + ' 00:00:00');

// Day of week (1=Sunday .. 7=Saturday for getDayOfWeekLocalTime())
var dowNum = gdt.getDayOfWeekLocalTime ? gdt.getDayOfWeekLocalTime() : gdt.getDayOfWeek(); // fallback
var names = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
// Map 1..7 → 0..6
var dowName = names[(dowNum - 1 + 7) % 7];

function addMonthsClone(srcGdt, n) {
var copy = new GlideDateTime(srcGdt);
copy.addMonthsLocalTime(n);
return copy.getDate().getValue(); // yyyy-MM-dd
}

var d3 = addMonthsClone(gdt, 3);
var d6 = addMonthsClone(gdt, 6);
var d12 = addMonthsClone(gdt, 12);

var payload = {
day_of_week: dowName,
date_plus_3m: d3,
date_plus_6m: d6,
date_plus_12m: d12
};
return new global.JSON().encode(payload);
},

type: 'DateCalcAjax'
});


2) Catalog Client Script (onChange on start_date)
-------------------------------------------------
Type: onChange
Applies to: Catalog Client Script
UI Type: All (Desktop, Mobile, Service Portal)
Variable name: start_date
Script:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading) return;
if (!newValue) {
g_form.clearValue('day_of_week');
g_form.clearValue('date_plus_3m');
g_form.clearValue('date_plus_6m');
g_form.clearValue('date_plus_12m');
return;
}

var ga = new GlideAjax('DateCalcAjax');
ga.addParam('sysparm_name', 'getOffsets');
ga.addParam('sysparm_start', newValue); // yyyy-MM-dd
ga.getXMLAnswer(function(ans) {
try {
var data = JSON.parse(ans || '{}');
if (data.day_of_week) g_form.setValue('day_of_week', data.day_of_week);
if (data.date_plus_3m) g_form.setValue('date_plus_3m', data.date_plus_3m);
if (data.date_plus_6m) g_form.setValue('date_plus_6m', data.date_plus_6m);
if (data.date_plus_12m) g_form.setValue('date_plus_12m', data.date_plus_12m);
} catch (e) {
console.log('Date calc parse error', e);
}
});
}

Notes & Tips
------------
- Ensure your variable names in the script (day_of_week, date_plus_3m, etc.) match the actual variable “Name” (not the label).
- Date variable values should be in yyyy-MM-dd format; the Script Include already returns that.
- If you also need to set an End Date, add logic in the Script Include to compute it and add to payload.
- This works in Classic UI, Service Portal, and Workspace.
- If you prefer a pure client approach (no server call), you can compute with JavaScript Date(), but you must handle timezones and month-end rollovers yourself. Example snippet below.

Pure client (optional alternative)
----------------------------------
function addMonthsYMD(ymd, months) {
// ymd: 'yyyy-MM-dd'
var parts = ymd.split('-');
var y = parseInt(parts[0],10), m = parseInt(parts[1],10)-1, d = parseInt(parts[2],10);
var dt = new Date(Date.UTC(y, m, d));
dt.setUTCMonth(dt.getUTCMonth() + months);
var yyyy = dt.getUTCFullYear();
var mm = String(dt.getUTCMonth()+1).padStart(2,'0');
var dd = String(dt.getUTCDate()).padStart(2,'0');
return yyyy + '-' + mm + '-' + dd;
}

function dayOfWeekName(ymd) {
var p = ymd.split('-');
var dt = new Date(Date.UTC(+p[0], +p[1]-1, +p[2]));
return ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][dt.getUTCDay()];
}